与前一个检查新整数有关的问题 [英] Issue with checking new integer against previous one

查看:244
本文介绍了与前一个检查新整数有关的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作类似于高低位游戏的东西.到目前为止,我可以得到一个介于1到25之间的新整数. 香港专业教育学院试图编写一个函数,当您按下降低"按钮时,它将检查前一个整数,然后检查下一个新整数,如果小于该整数,则会在下面显示您正确了"并更新用户得分+1的文本. ,如果显示错误,则会显示"You Were Wrong",并且将得分重置为0.

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 :)

下移按钮

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

随机数功能

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

使用的变量/常量

var countWin = 0
let countLose = 0

谢谢

推荐答案

到目前为止,我可以看到您的代码格式是否正确,您具有嵌套函数,但没有在函数内部调用它,因此函数lowerNumber()将被调用.您需要像下面的代码一样调用该函数:

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

尽管如此,嵌套函数是具有名称的闭包,可以从其闭包函数捕获值,因此您在使用它时需要谨慎.我推荐@AirSpeedVelocity的这篇文章,以了解有关闭包及其捕获值的更多信息

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

希望这对您有所帮助.

这篇关于与前一个检查新整数有关的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆