swiftswiftuiswiftui-foreachswiftui-state

SwiftUI: how to pass an array to a View to be used in ForEach


I would like to pass an array of elements to a View and show the elements with a ForEach. When I pass an array of a different size than the previous one, it crashes with error Thread 1: Fatal error: Index out of range on line Text(elements[$0]).

My code is like this:

struct ContentView: View {
    private let arrays = [["One", "Two", "Three"], ["Four", "Five"]]
    @State private var selectedArray = 0

    var body: some View {
        AnotherView(elements: arrays[selectedArray])

        Picker("Select Array", selection: $selectedArray) {
            ForEach(arrays.indices) {
                Text("Array \($0)")
            }
        }
    }
}

struct AnotherView: View {
    var elements: [String]

    var body: some View {
        VStack {
            ForEach(elements.indices) {
                Text(elements[$0])
            }
        }
    }
}

Is there a way to achieve the desired result?


Solution

  • ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!

    Try this:

    struct AntorherView: View {
    
        var elements: [String]
    
        var body: some View {
            VStack {
                ForEach(elements, id:\.self) { i in
                    Text(i)
                }
            }
        }
    }