ios 无法将“int”类型的值分配给“String”类型的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32362893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot assign a value of type 'int' to a value of type 'String?'
提问by Bader H Al Rayyes
Here is my code, I am a beginner using swift and my code does not work, the application should take the value of 'ageInput' textField and multiply it by 7 then show the results inside resultLabel, I always get the error:
这是我的代码,我是使用 swift 的初学者,我的代码不起作用,应用程序应该取 'ageInput' textField 的值并将其乘以 7 然后在 resultLabel 中显示结果,我总是得到错误:
Cannot assign a value of type 'int' to a value of type 'String?'
无法将“int”类型的值分配给“String”类型的值?
class ViewController: UIViewController {
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var ageInput: UITextField!
@IBAction func findAge(sender: AnyObject) {
var catAge = ageInput.text.toInt() ?? 0
catAge = catAge * 7 ?? 0
resultLabel.text = catAge
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
Where did i go wrong?
我哪里做错了?
回答by Andrey
Try:
尝试:
resultLabel.text = String (catAge)
回答by lucaslt89
You can also do:
你也可以这样做:
resultLabel.text = "\(catAge)"
回答by Akash Raghani
here i have tray to solve your problem using example and i hope your issue will solved..
在这里,我有托盘可以使用示例解决您的问题,我希望您的问题能够解决..
var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)
Note toInt():
注意到Int():
If the string represents an integer that fits into an Int, returns the corresponding integer.