gpt4 book ai didi

swift - 尝试连接字符串时出现 nill 错误

转载 作者:行者123 更新时间:2023-11-28 13:16:50 26 4
gpt4 key购买 nike

我遵循了教程并正确完成了所有操作。就在我尝试设置标签文本时,我可以在控制台中打印出年龄,但出现 nil 错误。

class ViewController: UIViewController {


@IBOutlet var inputField: UITextField!
@IBOutlet var outputLbl: UILabel!

@IBAction func enterBtn(sender: AnyObject) {

if(inputField != nil){

var age = inputField.text.toInt()
println(age)

var catYears = age! * 7
println(catYears)
outputLbl.text = "Your cat is \(catYears) old"
}
else {
outputLbl.text = "Please enter a age"
}
}

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

我阅读了文档并正确连接了字符串。然而就像我说的,当我取出下面的语句时:

outputLbl.text = "Your cat is \(catYears)  old"

程序运行良好。

最佳答案

我建议重构它以检查输入的文本是否能够转换为 int。您不应该检查 textField != nil 是否正确,因为如果 Storyboard正确加载,它不会为 nil。

考虑这个变化:

@IBAction func enterBtn(sender: UIButton) {

if let age = inputField.text.toInt() {
println(age)

var catYears = age * 7
println(catYears)
outputLbl.text = "Your cat is \(catYears) old"
} else {
outputLbl.text = "Please enter a valid age"
}
}

关于swift - 尝试连接字符串时出现 nill 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com