我想将元素数组传递给视图并使用 ForEach 显示元素。当我传递一个与前一个不同大小的数组时,它会Thread 1: Fatal error: Index out of range
因在线错误而崩溃Text(elements[$0])
。
我的代码是这样的:
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])
}
}
}
}
有没有办法达到预期的结果?