LoginSignup
10
9

[SwiftUI]for, ForEach, while, forEach の違いと使用例

Last updated at Posted at 2023-05-29

for, ForEach, while, forEachの区別がつかない!!!

for, while だけならわかるがForEachforEachとの違いがわからない。ということで自分用メモとしてもまとめました。

目次

結論としましては、Viewで使用できるか、どうかで大きく区別されます。

Viewを作成するときに使用できない

for, while, forEachViewを作成するときには使用できません。

それらの主な差は以下になります。

for : コレクションや範囲に対して反復操作を行うことができます。

while : 指定した条件が真(true)である限り、処理を繰り返します。

forEach : Swiftの配列(Array)やコレクションに含まれる標準メソッドです。配列の各要素に対して処理を行います。

Viewを作成するときに使用できる

ForEach:

  1. SwiftUIにおけるコレクションビューの作成に利用されます。配列の各要素に対して一連のビューを生成します。
  2. ForEachidを使用して配列の各アイテムを一意に識別します。これにより、データが変更されても、SwiftUIがどのビューを更新するべきかを正確に判断することが可能となります。

使用例

次に、それらの使い方を見ていきます。

PythonやCとは機能的には一緒でも、表記の仕方がかなり異なるイメージです。

for-inループ

1. 配列の要素を反復処理する:

let names = ["Alice", "Bob", "Charlie", "David"]

for name in names {
    print("Hello, \(name)!")
}

2. 辞書のキーと値を反復処理する:

let fruitColors = ["Apple": "Red", "Banana": "Yellow", "Grape": "Purple"]

for (fruit, color) in fruitColors {
    print("\(fruit) is \(color)") 
}

3. 範囲を反復処理する:

a. 範囲区間

x…y だと x≤ a ≤ y

for number in 1...5 {
    print("Number is \(number)")
}

// Number is 1
// Number is 2
// Number is 3
// Number is 4
// Number is 5

b. 半開放範囲

x..<y だと x≤ a < y

for number in 1..<5 {
    print("Number is \(number)")
}

// Number is 1
// Number is 2
// Number is 3
// Number is 4

4. 配列のインデックスと要素を同時に反復処理する:

enumerated()でindexと要素を両方取れる

indicesindexだけを取得するため、要素は取れない

indices.enumerated() にするとindexと要素両方取れる

let animals = ["Dog", "Cat", "Elephant", "Giraffe"]

for (index, animal) in animals.enumerated() {
    print("Index: \(index), Animal: \(animal)")
}

for index in animals.indices {
    print("Index: \(index), Animal: \(animal[index])")
}

for (index, animal) in animals.indices.enumerated() {
    print("Index: \(index), Animal: \(animal)")
}

5. stride() 関数を使った間隔を指定して反復処理する:

0≤ a < 10 で10が含まれないことに注意

for number in stride(from: 0, to: 10, by: 2) {
    print(number)
}

// 0
// 2
// 4
// 6
// 8.

6. 二次元配列の反復処理

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix {
    for element in row {
        print(element)
    }
}

7. 文字列を一文字ずつ反復処理

let greeting = "Hello, World!"

for character in greeting {
    print(character)
}

whileループ

1. while

while の対象となる値がtrueの間処理を続ける

(注) for と違いコードによっては無限ループになる可能性がある

var count = 1

while count <= 5 { //5を超えるまでル=プが回る
    print("Count is \(count)")
    count += 1  
}

2. Repeat-while

whileでは条件によっては一度も処理が実行されることがないときがあったが、Repeat-whileでは、少なくとも一回はループ内の処理を行う。

var number = 0

repeat {
    number += 1
    print("Number is \(number)")
} while number < 5

for-Each

基本の構文

array.forEach { value in
		//arrayの要素がvalueに割り当てられ、valueとして扱える。
}

1. 配列に対して使用した例

let numbers = [1, 2, 3, 4, 5]

numbers.forEach { number in
    print("Number is \(number)")
}

2. 辞書に対して使用した例

let fruitColors = ["Apple": "Red", "Banana": "Yellow", "Grape": "Purple"]

fruitColors.forEach { (fruit, color) in
    print("\(fruit) is \(color)")
}

3. セットに対して使用した例

let uniqueNumbers: Set = [1, 2, 3, 4, 5]

uniqueNumbers.forEach { number in
    print("Number is \(number)")
}

ForEach

1. 配列の各要素に対してテキストビューを作成する例:

struct ContentView: View {
    let names = ["Alice", "Bob", "Charlie", "Dave"]

    var body: some View {
        VStack {
            ForEach(names, id: \.self) { name in
                Text(name)
            }
        }
    }
}

このコードでは、namesという配列の各要素に対して、その要素の値を表示するTextビューが作成されます。結果として、"Alice", "Bob", "Charlie", "Dave"というテキストが垂直に並べられたビューが生成されます。

2. リストビュー内でForEachを使用する例:

struct ContentView: View {
    let todos = ["Buy groceries", "Finish homework", "Clean the house"]

    var body: some View {
        List {
            ForEach(todos, id: \.self) { todo in
                Text(todo)
            }
        }
    }
}

この例では、todosという配列の各要素に対してリストの行が生成されます。ForEachはリストビュー、ナビゲーションビュー、またはその他のシーケンスビュー内でよく使用されます。

3. ForEachでデータとともに配列のインデックスも取得する例:

struct ContentView: View {
    let names = ["Alice", "Bob", "Charlie", "Dave"]

    var body: some View {
        List(Array(names.enumerated()), id: \.element) { (index, name) in
            Text("\(index + 1). \(name)")
        }
    }
}


//indicesでも同様の処理ができる
struct ContentView: View {
    let names = ["Alice", "Bob", "Charlie", "Dave"]

    var body: some View {
        List {
            ForEach(names.indices, id: \.self) { index in
                Text("\(index+1). \(names[index])")
            }
        }
    }
}

image.png

この例では、names配列の各要素とそのインデックスを取得しています。enumerated()関数とArray() イニシャライザを使用することで、インデックスと要素のペアの新しい配列を作成し、それをForEachでループしています。

forとfor-Eachの違いは?

for-Eachではbreak,continue が使えない

for-Eachは関数であり、forは演算子であるため、関数型プログラミングに使用できる

まとめ

今回は、Swiftにおける。for, ForEach, while, forEachの使い方をまとめました。

Viewの生成に使えるかってのが、Swiftならではですね。

何かご指摘やアドバイス等あればお待ちしております。

いいね、ブックマーク、フォローしていただけると勉強の励みになりますので是非お願いします。😉

-- 追伸 --
Twitterで日々の学習風景を投稿してます。
https://twitter.com/Ren_yello

参考にさせていただいたサイト

10
9
1

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
10
9