Swift如果else语句没有按预期工作

时间:2016-08-05 15:57:16

标签: swift integer comparison optional

我试图为类似于高/低游戏的游戏制作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)"
}

1 个答案:

答案 0 :(得分:3)

您正在将Int值与nil类型Int?的值进行比较

var newNumber = 10
var oldNumber: Int?

if newNumber <= oldNumber {
    print("<=")
} else {
    print("Not <=")
}

结果

Not <=

在Swift中,Int不是<=而不是nil,这就是执行else分支的原因。

建议

lowerNumber是一种非常奇怪的方法:

  1. 它不需要参数
  2. 它返回最小值
  3. 并且还执行一些操作
  4. 我建议你把它改成像这样的东西

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