Jeremy - 1 year ago 77
Swift Question

# Issue with checking new integer against previous one

Im attempting to make something similar to the high low game. So far i can get a new integer between 1-25 to be generated.
Ive tried to write a function that when you press the 'lower' button it checks the new integer against the previous one, and if it is less then text is displayed below saying 'You Were Correct' and updates the users score +1.. and if wrong 'You Were Wrong' displays instead and score is reset to 0.

Whenever i press the lower button it gives me a new int but score is not updated and the message doesn't display. This is my first real attempt at making this so bear with me :)

Lower Button

``````    @IBAction func lower(sender: AnyObject) {
var newNumber = randomIntBetween(2, high: 26)
var oldNumber: Int?

func lowerNumber() -> Int {
if newNumber <= oldNumber {
correctWrong.text = "You Were Correct!"
score.text = "Score: \(countWin++)"
} else {
correctWrong.text = "You Were Wrong!"
score.text = "Score: \(countLose)"
}
return newNumber
}
randomNumbers.text = "\(newNumber)"
}
``````

Random Number Function

``````    func randomIntBetween(low:Int, high:Int) -> Int {
let range = high - (low - 1)
return (Int(arc4random()) % range) + (low - 1)
}
``````

Variables/Constants Used

``````var countWin = 0
let countLose = 0
``````

Thanks

As far I can see if your code it's formatted correctly you have a nested function but you aren't calling it inside your function so it's impossible that the function `lowerNumber()` will be called. You need to call the function like the following code:

``````@IBAction func lower(sender: AnyObject) {
var newNumber = randomIntBetween(2, high: 26)
var oldNumber: Int?

func lowerNumber() -> Int {
if newNumber <= oldNumber {
correctWrong.text = "You Were Correct!"
score.text = "Score: \(countWin++)"
} else {
correctWrong.text = "You Were Wrong!"
score.text = "Score: \(countLose)"
}
return newNumber
}

let newValue = lowerNumber()
randomNumbers.text = "\(newValue)"
}
``````

Nevertheless, nested functions are closures that have a name and can capture values from their enclosing function so you need to be carefully with its use. I recommend this article of @AirSpeedVelocity to learn more about the closures and its capture values A Basic Tutorial on Functions and Closures in Swift