0

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?

1 Answer 1

1

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)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.