简单的 SwiftUI 列表示例。我究竟做错了什么?

Simple SwiftUI List example. What am I doing wrong?

我在将字符串数据绑定到列表中的文本时遇到问题。不确定我做错了什么。

这是一个简单的修复。当你传递一个数组给List时,数组中的元素需要符合Identifiable协议。 String 不符合 Identifiable,因此实现此功能的方法是像这样使用 .identified(by:)

struct StringList: View {
    let strings = ["1234", "5678"]

    var body: some View {
        List(strings.identified(by: \.self)) { string in
            Text(string)
        }
    }
}

你也可以在List里面使用ForEach:

struct StringList: View {
    let strings = ["1234", "5678"]

    var body: some View {
        List {
            ForEach(strings.identified(by: \.self)) { string in
                Text(string)
            }
        }
    }
}

这两个示例都实现了相同的输出,但第一个更清晰,需要的代码更少。

更新

从 Xcode Beta 4 开始,identified(by:) 已被弃用,取而代之的是 ListForEach 的特定初始化程序:

struct StringList: View {
    let strings = ["1234", "5678"]

    var body: some View {
        List(strings, id: \.self) { string in
            Text(string)
        }
    }
}
struct StringList: View {
    let strings = ["1234", "5678"]

    var body: some View {
        List {
            ForEach(strings, id: \.self) { string in
                Text(string)
            }
        }
    }
}