Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 我的代码有什么问题?5+;5将给我55而不是10_Swift_Addition - Fatal编程技术网

Swift 我的代码有什么问题?5+;5将给我55而不是10

Swift 我的代码有什么问题?5+;5将给我55而不是10,swift,addition,Swift,Addition,我的代码有什么问题?例如,5+5将给我55而不是10。有人能指出我的错误吗?您正在将一个字符串添加到另一个字符串中: @IBAction func calcAns(sender: UIButton) { result = firstNumber.text + secondNumber.text outputLabel.text = "\(result)" } 如果firstNumber.text是“Hello”,而secondNumber.text是“World”,则结果将是

我的代码有什么问题?例如,5+5将给我55而不是10。有人能指出我的错误吗?

您正在将一个字符串添加到另一个字符串中:

@IBAction func calcAns(sender: UIButton) {

   result = firstNumber.text + secondNumber.text
   outputLabel.text = "\(result)"


}
如果
firstNumber.text
是“Hello”,而
secondNumber.text
是“World”,则结果将是“HelloWorld”。实际上,您将“5”和“5”连接起来,得到“55”


解决方案是在将这些字符串相加之前将其转换为数值。

您需要将字符串变量转换为int:

firstNumber.text + secondNumber.text

在Swift中,字符串上的
+
是串联而不是加法。
text
属性是字符串而不是数字

要将其转换为数字,请尝试:

@IBAction func calcAns(sender: UIButton) {

   result = firstNumber.text.toInt() + secondNumber.text.toInt()
   outputLabel.text = "\(result)"


}

您的变量被视为字符串而不是int,您需要将其转换为int(或强制转换为int)
5+5=10
,但
“5”+“5”=“55”
。不要忘记向上投票和/或接受下面的答案,以表达对您所获得帮助的感谢。谢谢
if let first = firstNumber.text.toInt(),
       second = secondNumber.text.toInt() {

    outputLabel.text = toString(first + second)

}