-1

我想将元素数组传递给视图并使用 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])
            }
        }
    }
}

有没有办法达到预期的结果?

4

1 回答 1

1

ForEach(_:content:)应该只用于常量数据。而是使数据符合Identifiable或使用ForEach(_:id:content:)并提供明确的id!

尝试这个:

struct AntorherView: View {

    var elements: [String]

    var body: some View {
        VStack {
            ForEach(elements, id:\.self) { i in
                Text(i)
            }
        }
    }
}
于 2021-01-12T15:06:05.657 回答