如果 - 否则 Swift

If - else in Swift

我可以显示警报,但它有一些问题:

  1. 标题没有出现
  2. 我无法使 if 语句部分起作用。弹出的警报仅显示:

    the message numbers must be 24 or less

    连同关闭按钮,永不改变。

使用 XCode 6.3 和 iOS 8.

var title: String!

if difference > hoursLabel {
    title = "Sorry!"
}
else if difference < hoursLabel {
    title = "That's better!"
}

let message =  "Number must be 24 or less"
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))

self .presentViewController(alert, animated: true, completion: nil)

根据您提供的内容,问题似乎出在使用 else if,而不是仅 else

解决方案一:

var title: String!

if difference > hoursLabel {
    title = "Sorry!"
}
else {
    title = "That's better!"
}

方案二:

let title = (difference > hoursLabel) ? "Sorry": "That's better!" ;