Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through an array in SwiftUI

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading