Swift 我的代码有什么问题?5+;5将给我55而不是10
我的代码有什么问题?例如,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”,则结果将是
@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)
}