Swift-fallthrough-statement
提供:Dev Guides
Swift-フォールスルーステートメント
Swift 4のswitchステートメントは、CおよびC ++プログラミング言語で発生する後続のケースの最下部を通過するのではなく、最初に一致したケースが完了するとすぐに実行を完了します。
CおよびC ++でのswitch文の一般的な構文は次のとおりです-
switch(expression){
case constant-expression :
statement(s);
break;/*optional*/
case constant-expression :
statement(s);
break;/*optional*/
/*you can have any number of case statements*/
default :/*Optional*/
statement(s);
}
ここでは、caseステートメントから抜け出すために break ステートメントを使用する必要があります。そうしないと、実行制御は、一致するcaseステートメントの下で使用可能な後続のcaseステートメントを通過します。
構文
Swift 4のswitch文の一般的な構文は次のとおりです-
switch expression {
case expression1 :
statement(s)
fallthrough/*optional*/
case expression2, expression3 :
statement(s)
fallthrough/*optional*/
default :/*Optional*/
statement(s);
}
*fallthrough* ステートメントを使用しない場合、一致するcaseステートメントを実行した後、プログラムは *switch* ステートメントから抜け出します。 機能を明確にするために、次の2つの例を取り上げます。
例1
次の例は、Swift 4プログラミングでswitchステートメントを使用する方法を示しています*フォールスルーなし*-
var index = 10
switch index {
case 100 :
print( "Value of index is 100")
case 10,15 :
print( "Value of index is either 10 or 15")
case 5 :
print( "Value of index is 5")
default :
print( "default case")
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Value of index is either 10 or 15
例2
次の例は、Swift 4プログラミングで* switchthroughを使用してswitchステートメントを使用する方法を示しています-
var index = 10
switch index {
case 100 :
print( "Value of index is 100")
fallthrough
case 10,15 :
print( "Value of index is either 10 or 15")
fallthrough
case 5 :
print( "Value of index is 5")
default :
print( "default case")
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Value of index is either 10 or 15
Value of index is 5