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