Xcode中的流控制

时间:2015-08-07 19:11:37

标签: ios xcode

由于某种原因,即使输入有效的输入,即整数,它似乎也会进入函数@IBAction func guess(sender: UIButton){}中的if语句。换句话说,如果我输入5,控制台输出将显示"请输入有效数字。"不是"你猜到了高"或者"你猜到了#34;或者"你赢了!"。关于如何解决这个问题的任何建议?

以下是我的代码:

class ViewController: UIViewController {

    //just some member variables. I don't think the problem is here. 
    @IBOutlet weak var inputField: UITextField!
    @IBOutlet weak var output: UITextView!
    var guesses : UInt = 0;
    var number : UInt32 = 0;
    var gameover = false;
    let MAX_GUESSES = 8;
    var possibleGuess : Int?

    override func viewDidLoad() {
        super.viewDidLoad()
        number = generateNewNumber()
        consoleOut("I'm thinking of a number...\n")
        var possibleGuess : Int? = inputField.text.toInt()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //consoleOut here prints out stuff on the app. 
    func consoleOut(text : String) {
        output.text = output.text + text;
    }

    func generateNewNumber() -> UInt32 {
        return arc4random_uniform(100) + 1
    }

    func clearInput() {
        output.text = ""
    }

    //here lies the problem. The control never seems to go inside of
    //if let guess = possibleGuess{}
    @IBAction func guess(sender: UIButton) {
        if let guess = possibleGuess {
            if UInt32(guess) > number {
                consoleOut("\(guess): You guessed to high\n")
                ++guesses
            }
            else if UInt32(guess) < number {
                consoleOut("\(guess): You guessed to low\n")
                ++guesses
            }
            else {
                consoleOut("\(guess): You win!\n")
                consoleOut("Go again? (y/n)")
                guesses = 0
                gameover = true
            }
            clearInput()
        }
        else {
            clearInput()
            consoleOut("Please input a valid number")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个非常常见的错误。

您将变量possibleGuess声明为可选的Int实例变量,但稍后您在viewDidLoad()中声明一个名称相同的变量,其范围仅在viewDidLoad()范围内方法

解决方案:删除var方法中的viewDidLoad()关键字。

possibleGuess = inputField.text.toInt()

由于已经定义了类型,因此不需要显式类型注释。