Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

swift - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...