我的代码出了什么问题? 5 + 5会给我55而不是10

时间:2015-03-19 09:01:02

标签: swift addition

@IBAction func calcAns(sender: UIButton) {

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


}

我的代码出了什么问题?例如5 + 5会给我55而不是10.有人可以指出我的错误吗?

3 个答案:

答案 0 :(得分:2)

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

firstNumber.text + secondNumber.text

如果firstNumber.text为“Hello”且secondNumber.text为“World”,则结果为“HelloWorld”。实际上,你将“5”和“5”联系起来得到“55”。

解决方案是将这些字符串转换为数字值,然后再将它们组合在一起。

答案 1 :(得分:1)

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

@IBAction func calcAns(sender: UIButton) {

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


}

答案 2 :(得分:1)

在Swift中,字符串上的+是连接而不是添加。 text属性是字符串而不是数字。

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

if let first = firstNumber.text.toInt(),
       second = secondNumber.text.toInt() {

    outputLabel.text = toString(first + second)

}