
スイフトループ
コードブロックを何度も実行する必要がある場合があります。一般に、文は順番に実行されます。関数内の最初の文が最初に実行され、次に次の文が実行されます。
プログラミング言語は、より複雑な実行経路を可能にする様々な制御構造を提供します。
ループステートメントは、ステートメントまたはステートメントのグループを複数回実行することを可能にします。以下は、ほとんどのプログラミング言語におけるループ文の一般的なものです。
詳細を確認するには、以下の内容を確認ください
Sr.No | ループタイプと説明 |
---|---|
1 | for-inこのループは、範囲、シーケンス、コレクション、または進行中の各アイテムの一連のステートメントを実行します。
var someInts:[Int] = [10, 20, 30] for index in someInts { print( "Value of index is \(index)") } 上記のコードを実行すると、次の結果になります。 Value of index is 10 Value of index is 20 Value of index is 30 |
2 | whileループ
var index = 10 while index < 20 { print( "Value of index is \(index)") index = index + 1 } indexの値が20未満の場合、whileループは、その隣にあるコードブロックを実行し続け、indexの値が等しくなると終了。実行されると、次の結果に。 Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19 与えられた条件が真である間、ステートメントまたはステートメントのグループを繰り返します。ループ本体を実行する前に条件をテストします。 |
3 | repeat …
whileループwhileステートメントと似ていますが、ループ本体の最後の条件をテストする点が異なります。 var index = 10 repeat { print( "Value of index is \(index)") index = index + 1 } while index < 20 上記のコードを実行すると、次の結果が生成されます。 Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19 |
ループ制御文
ループ制御ステートメントは、通常のシーケンスから実行を変更します。実行がスコープを離れると、そのスコープで作成されたすべての自動オブジェクトが破棄されます。
Swift 4は以下の制御文をサポートしています。詳細を確認するには、以下のリンクをクリックしてください。
Sr.No | コントロールステートメントと説明 |
---|---|
1 | 継続声明
このステートメントは、ループに何をしているのかを知らせ、ループを介して次の反復の開始時に再び開始するように指示します。
var index = 10 repeat { index = index + 1 if( index == 15 ){ continue } print( "Value of index is \(index)") } while index < 20 上記のコードをコンパイルして実行すると、次の結果が生成されます。 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19 Value of index is 20 |
2 | breakステートメント
ループ文を終了し、ループの直後の文に実行を転送します。
var index = 10 repeat { index = index + 1 if( index == 15 ){ break } print( "Value of index is \(index)") } while index < 20 上記のコードをコンパイルして実行すると、次の結果が生成されます。 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14
|
3 | フォールスルーステートメント
Swift 4のswitch文は、CおよびC ++プログラミング言語で起こるように、最初の一致するケースが完了するとすぐに実行を終了してしまいます。 CおよびC ++のswitch文の一般的な構文は次のとおりです。 switch(expression){ case constant-expression : statement(s); break; case constant-expression : statement(s); break; default : statement(s); } ここでは、case文から出るためにbreak文を使う必要があります。 フォールスルーステートメントは、Swift 4スイッチのCスタイルスイッチへの動作をシミュレートします。 SWIFTの場合は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ステートメントからプログラムが出力されます。
|
前のページ 次のページ