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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…