Swift嵌套 if 语句
在 Swift 中嵌套 if-else 语句始终是合法的,这意味着可以使用一个 if 或 else if 语句在另一个 if 或 else if 语句中。
语法
嵌套 if 语句的语法如下:
if boolean_expression_1 { /* Executes when the boolean expression 1 is true */ if boolean_expression_2 { /* Executes when the boolean expression 2 is true */ } }
可以嵌套 else if...else 类似 if 语句的方式。
示例
import Cocoa var varA:Int = 100; var varB:Int = 200; /* Check the boolean condition using if statement */ if varA == 100 { /* If condition is true then print the following */ println("First condition is satisfied"); if varB == 200 { /* If condition is true then print the following */ println("Second condition is also satisfied"); } } println("Value of variable varA is \(varA)"); println("Value of variable varB is \(varB)");
当上述代码被编译和执行时,它产生了以下结果:
First condition is satisfied Second condition is also satisfied Value of variable varA is 100 Value of variable varB is 200