在 Swift 中嵌套 if-else 語(yǔ)句始終是合法的,這意味著可以使用一個(gè) if 或 else if 語(yǔ)句在另一個(gè) if 或 else if 語(yǔ)句中。
嵌套 if 語(yǔ)句的語(yǔ)法如下:
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 語(yǔ)句的方式。
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)");
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
First condition is satisfied Second condition is also satisfied Value of variable varA is 100 Value of variable varB is 200