本教程属于Swift系列
if 语句是执行条件检查的最常用方式。我们使用 关键字,后面是一个布尔表达式,然后是一个包含代码的块,如果条件为真,就会运行。if
let condition = true
if condition == true {
// code executed if the condition is true
}
如果条件为假,则执行一个else 块。
let condition = true
if condition == true {
// code executed if the condition is true
} else {
// code executed if the condition is false
}
如果你愿意,你可以选择将条件验证包在圆括号里。
if (condition == true) {
// ...
}
Swift与其他许多语言不同的一点是,它可以防止因错误地进行赋值而不是比较而造成的错误。这意味着你不能这样做。
if condition = true {
// The program does not compile
}
和的原因是,赋值运算符不返回任何东西,但if 条件必须是一个布尔表达式。