Swift ForEachで配列の要素を取得するサンプル

環境
Swift version 5.2.3 (swift-5.2.3-RELEASE)
Ubuntu 20.04.2 LTS

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ForEach (配列変数名, id: \.self) { item in
//処理コード
}
ForEach (配列変数名, id: \.self) { item in //処理コード }
ForEach (配列変数名, id: \.self) { item in
//処理コード
}

第1引数に配列を指定します。
第2引数「id」に「\.self」を指定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
struct ContentView: View {
let citys = ["東京", "大阪", "福岡", "横浜"]
var body: some View {
VStack {
ForEach(citys, id: \.self) { cs in
Text(cs)
.padding()
}
}
}
}
struct ContentView: View { let citys = ["東京", "大阪", "福岡", "横浜"] var body: some View { VStack { ForEach(citys, id: \.self) { cs in Text(cs) .padding() } } } }
struct ContentView: View {
    let citys = ["東京", "大阪", "福岡", "横浜"]
    
    var body: some View {
        VStack {
            ForEach(citys, id: \.self) { cs in
                Text(cs)
                    .padding()
            }
        }
    }
}

 

Swift

Posted by arkgame