gpt4 book ai didi

swift - 为什么 swift 不会重新计算 'if' 语句?

转载 作者:行者123 更新时间:2023-11-28 06:44:22 24 4
gpt4 key购买 nike

我正在尝试创建一个非常简单的“猜谜游戏”,用户必须猜测计算机有多少根手指(最多 5 根手指)。

事情是这样的。当代码执行并且我按下提交时,即使打印日志注册了正确的数字,应用程序仍会打印 if 语句以表示不正确。我哪里错了?

import UIKit

类 ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

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




@IBOutlet weak var fingerInput: UITextField!

@IBOutlet weak var fingerResult: UILabel!

@IBAction func fingerSubmit(sender: AnyObject) {

let realNumberofFingers = Int(arc4random_uniform(6))

print(realNumberofFingers)

if fingerInput != realNumberofFingers {

fingerResult.text = "Gosh darn, that's wrong!"

} else if fingerInput == realNumberofFingers {

fingerResult.text = "Thats right!"

}
}

最佳答案

您正在比较 actual UITextField fingerInputrealNumberofFingers。这是错误的,并且总是会产生 false。您应该做的是解析 fingerInput 中的字符串并检查该字符串中包含的整数是否等于 realNumberofFingers:

@IBAction func fingerSubmit(sender: AnyObject) {

let input = Int(fingerInput.text!)

if let enteredFingers = input {
let realNumberofFingers = Int(arc4random_uniform(6))
print(realNumberofFingers)

if enteredFingers == realNumberofFingers {
fingerResult.text = "Thats right!"
} else {
fingerResult.text = "Gosh darn, that's wrong!"
}
} else {
fingerResult.text = "Please enter a correct guess - an integer!"
}
}

关于swift - 为什么 swift 不会重新计算 'if' 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968483/

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