Swift-if-else-if-else-statement

提供:Dev Guides
移動先:案内検索

Swift-if …​ else if …​ elseステートメント

*if* ステートメントの後にオプションの *else if ... else* ステートメントを続けることができます。これは、単一のif ... else ifステートメントを使用してさまざまな条件をテストするのに非常に便利です。
*if、else if、else* ステートメントを使用する場合、留意すべき点がいくつかあります。
  • if には0個または1個の else を含めることができ、他のifの後に来る必要があります。
  • if は0個以上の else if を持つことができ、elseの前に来る必要があります。
  • else if が成功すると、残りの else if または else はテストされません。

構文

Swift 4の 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*/
}

var varA:Int = 100;

/*Check the boolean condition using if statement*/
if varA == 20 {
  /*If condition is true then print the following*/
   print("varA is equal to than 20");

} else if varA == 50 {
  /*If condition is true then print the following*/
   print("varA is equal to than 50");

} else {
  /*If condition is false then print the following*/
   print("None of the values is matching");
}

print("Value of variable varA is \(varA)");

上記のコードをコンパイルして実行すると、次の結果が生成されます-

None of the values is matching
Value of variable varA is 100