thumbtackthief
thumbtackthief

Reputation: 6221

Declare a variable in ViewDidLoad and use elsewhere (Swift)

First Swift project, and I'm confused as to how scope works. I'm trying to choose a random integer in ViewDidLoad and then allow the user to guess the number, but I can't work out how to access the variable answer created in ViewDidLoad in my button action.

class ViewController: UIViewController {

    @IBOutlet var guess: UITextField!

    @IBOutlet var result: UILabel!

    @IBAction func guessButton(sender: AnyObject) {

        var userGuess = guess.text.toInt()
        if userGuess != nil {
            if userGuess == answer {
                result.text = "You got it!"
            } else if userGuess > answer {
                result.text = "Too high! Guess again!"
            } else {
                result.text = "Too low!  Guess again!"
            }
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        var answer = arc4random_uniform(100) + 1

        }
   }

Upvotes: 0

Views: 2097

Answers (1)

matt
matt

Reputation: 535890

Three scopes:

  • File top level

  • Object type declaration top level (like your guess)

  • Local (inside function curly braces) (like your userGuess)

You can only see up (higher surrounding scope).

So, code in guessButton method cannot see variable declared in viewDidLoad method. But they can both see variable declared at file top level or variable declared at object type declaration top level. Which one do you think is most appropriate here?

Upvotes: 2

Related Questions