为什么不快速重新计算“如果'声明?

时间:2016-05-01 15:35:52

标签: swift if-statement

我试图制作一个非常简单的猜谜游戏'用户必须猜测计算机有多少手指(最多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!"

    }
}

}

1 个答案:

答案 0 :(得分:1)

您正在将实际 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!"
    }
}