Issue with checking new integer against previous one

試著忘記壹切 提交于 2020-01-07 03:44:10

问题


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


回答1:


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

I hope this help you.



来源:https://stackoverflow.com/questions/38769525/issue-with-checking-new-integer-against-previous-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!