Home > Enterprise >  Looping through an array in SwiftUI
Looping through an array in SwiftUI

Time:02-07

I have an array of strings I want to loop through and create a view for each element. To achieve that, I tried using ForEach(), the output of the code below are the following errors:

Cannot convert value of type '[String]' to expected argument type 'Binding<C>'

Generic parameter 'C' could not be inferred

Code:

struct HomeView: View {
    let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]

    var body: some View {
        VStack {
            ForEach(array, id: \.self) { letter in
                Text(array[letter])
            }
        }
    }           
}

PS: The code is simplified

Desired output:

VStack of all letters from the array

CodePudding user response:

You can try this (just use the letter parameter from the for loop):

let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]

var body: some View {
    VStack {
        ForEach(array, id: \.self) { letter in
            Text(letter)
        }
    }
}
  •  Tags:  
  • Related