aejhyun
aejhyun

Reputation: 612

Flow Control in Xcode

For some reason, even if input a valid input, namely, an integer, it does seem to go into if statement in the function, @IBAction func guess(sender: UIButton){}. In other words, if I input 5, the console output will say "Please input a valid number." Not "you guessed to high" or "you guessed to low" or "you win!". Any suggestion on how to fix this?

The following is my code:

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")
        }
    }
}

Upvotes: 0

Views: 130

Answers (1)

vadian
vadian

Reputation: 285072

This is a very common mistake.

You declare a variable possibleGuess as optional Int instance variable, but later you declare a variable with the same name in viewDidLoad() whose scope is locally only within the viewDidLoad() method.

Solution : delete the var keyword in the viewDidLoad() method.

possibleGuess = inputField.text.toInt()

The explicit type annotation is not needed too as the type has been already defined.

Upvotes: 1

Related Questions