我试图为类似于高/低游戏的游戏制作if else语句。当您单击该按钮时,似乎该语句正在跳过if NewNumber <= oldNumber
部分并直接转到其他部分。它应检查旧整数的新整数,看它是高还是低。
只是做了一会儿,所以我不确定我做错了什么
//Lower Button
@IBAction func lowerButton(sender: AnyObject) {
var newNumber = randomIntBetween(2, high: 26)
var oldNumber: Int?
func lowerNumber() -> Int {
if newNumber <= oldNumber {
correctWrongLabel.text = "You Were Correct!"
scoreLabel.text = "Score: \(countWin++)"
} else {
correctWrongLabel.text = "You Were Wrong!"
scoreLabel.text = "Score: \(countLose)"
}
return newNumber
}
let newValue = lowerNumber()
randomIntLabel.text = "\(newValue)"
}
答案 0 :(得分:3)
您正在将Int
值与nil
类型Int?
的值进行比较
var newNumber = 10
var oldNumber: Int?
if newNumber <= oldNumber {
print("<=")
} else {
print("Not <=")
}
结果
Not <=
在Swift中,Int
不是<=
而不是nil
,这就是执行else分支的原因。
lowerNumber
是一种非常奇怪的方法:
我建议你把它改成像这样的东西
func updateUI(old: Int, new: Int) {
if new <= old {
correctWrongLabel.text = "You Were Correct!"
scoreLabel.text = "Score: \(countWin++)"
} else {
correctWrongLabel.text = "You Were Wrong!"
scoreLabel.text = "Score: \(countLose)"
}
}
然后,在您的代码中,您需要获得2个值之间的最小值,只需使用min
if let oldNumer = oldNumber {
let minimum = min(newNumber, oldNumber)
}