一個(gè) if 語句可以跟著一個(gè)可選的 else if ... else 語句,單個(gè) if...else if 語句用來測(cè)試各種條件是非常有用的。
當(dāng)使用 if , else if , else 語句時(shí)有幾點(diǎn)要牢記。
以下是 if...else if...else 語句的語法:
if boolean_expression_1 {
/* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
/* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
import Cocoa
var varA:Int = 100;
/* Check the boolean condition using if statement */
if varA == 20 {
/* If condition is true then print the following */
println("varA is equal to than 20");
} else if varA == 50 {
/* If condition is true then print the following */
println("varA is equal to than 50");
} else {
/* If condition is false then print the following */
println("None of the values is matching");
}
println("Value of variable varA is \(varA)");
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
None of the values is matching Value of variable varA is 100