0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】繰り返し文について〜for-in文〜

Last updated at Posted at 2020-12-07

繰り返し文の種類

繰り返し処理を行う代表的な制御構文には、for-in文while文が存在します。

for-in文はシーケンスの要素数によって、
while文は継続条件の評価によって繰り返しの終了を決定します。

また、repeat-while文という制御構文も存在します。
repeat-while文は実行文の初回実行を保証する制御構文になります。

for-in文

for-in文は、Sequenceプロトコルに準拠している型の要素にアクセスするための制御構文です。

Sequenceプロトコルに準拠している代表的な型には、
Array<Element>型Dictionary<Key, Value>型などがあります。

for-in文は次のように記述します。
要素名は基本的になんでも構いませんが、
意味のある分かりやすい要素名にした方が分かりやすくなります。


for 要素名 in シーケンス {
   要素ごとに繰り返し実行される処理
}

Array<Element>型

Array<Element>型の要素をfor-in文で列挙する場合、要素の型はElement型になります。
つまり、Array<Int>型の要素をfor-in文で取り出す場合の要素の型はInt型になります。

let arrayInt = [1, 2, 3, 4, 5]
var count = 0

for int in arrayInt {
    count += int
}

print(count)

実行結果
15

arrayIntの中に格納されている要素を先頭から順に取り出して、
for int in arrayIntのintの中に代入しています。

for-in文の中の処理を全て終えるとarrayIntの次の要素にアクセスしintに入れる。
それをarrayIntの先頭から末尾まで繰り返していきます。

Dictionary<Key, Value>型

Dictionary<Key, Value>型の要素をfor-in文で列挙する場合、
要素の型は、(Key, value)型のタプルとなります。

例えば、Dictionary<String, Int>型の値をfor-in文に渡すと、
要素は(String, Int)型になります。

なお、Dictionary<Key, Value>型は要素の順序を保証していないため、
環境によっては実行結果の順序が異なるかもしれません。


let dictionary = ["a": 1, "b": 2]

for (key, value) in dictionary {
    print("Key: \(key), Value: \(value)")
}

実行結果
Key: a, Value: 1
Key: b, Value: 2

Range<Bound>型

また、範囲型についてもfor-in文で回すことが可能です。

今回は、1から10までの値を順にitemに代入しそれらを足す処理を行っています。

var count = 0

for item in 1...10 {
    count += item
}

print(count)

実行結果
55

これらが代表的なfor-in文になります。

個人的にはif文より使用頻度は低いと思いますが、
かなり重要な制御構文なので絶対に覚えた方が良いと思います。

以上、最後までご覧いただきありがとうございました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?