Swift if...else语句
一个 if 语句可以跟着一个可选的 else 语句,当布尔表达式为假时,else 语句块执行。
语法
一个 if ... else 语句在 Swift 中的语法如下:
if boolean_expression { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
如果布尔表达式的值为true,那么 if 代码块将被执行,否则 else 代码块将被执行。
流程图
示例
var varA:Int = 101; /* Check the boolean condition using if statement */ if varA < 20 { /* If condition is true then print the following */ println("varA is less than 20"); } else { /* If condition is false then print the following */ println("varA is not less than 20"); } println("Value of variable varA is \(varA)");
当上述代码被编译和执行时,它产生了以下结果:
varA is not less than 20 Value of variable varA is 101