Mike BRA Mike BRA - 5 months ago 9
Swift Question

Generating a random number under super.ViewDidLoad

I am making a 'Guess The Number' Game for a project at school, I want my application to generate one random number between 1-10 and then let me use it under my button which allows the user to guess the number by entering their guess into a text field. I have managed to do some of this, my random number generator is currently under my 'Guess' Button which means every time they press the button the number will change. My solution is to generate a number under super.ViewDidLoad and then use it under the button to do the rest. But im not sure how to do this! Please Help!

Answer

If I've understood you correctly you want the number to be generated only once instead of on every press.

So you might want something like this:

var randomNumber: Int

override func viewDidLoad() {
    super.viewDidLoad()

    //Initialization
    generateRandomNumber()
}

func generateRandomNumber() {
    randomNumber = Int(arc4random_uniform(9)) + 1
}

randomNumber is an instance-variable, so you can access it in all of your methods, for example to check if the user guessed correctly.