我试图制作类似于高低游戏的东西。到目前为止,我可以得到1-25之间的新整数。 我试过写一个功能,当你按下' lower'按钮它检查新的整数与前一个整数,如果它小于那么文本显示在下面说“你是正确的”'并更新用户得分+1 ..如果错误'你错了'而是显示并将分数重置为0.
每当我按下按钮时,它会给我一个新的int,但分数不会更新,并且消息不会显示。这是我第一次真正尝试让我这么做:)
下按钮
@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
由于
答案 0 :(得分:0)
到目前为止,我可以看到你的代码是否格式正确,你有一个嵌套函数,但你没有在函数内调用它,所以函数lowerNumber()
是不可能的将被召唤。您需要像下面的代码一样调用函数:
@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的这篇文章来了解有关闭包及其捕获值的更多信息A Basic Tutorial on Functions and Closures in Swift
我希望这对你有所帮助。