我试图制作一个非常简单的猜谜游戏'用户必须猜测计算机有多少手指(最多5个手指)。
这就是事情。当代码执行并按下提交时,即使打印日志注册了正确的数字,应用程序仍会打印if语句不正确。我哪里错了?
import UIKit
class 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!"
}
}
}
答案 0 :(得分:1)
您正在将实际 UITextField
fingerInput
与realNumberofFingers
进行比较。这是错误的,总是会产生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!"
}
}