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