代码之家  ›  专栏  ›  技术社区  ›  fs_tigre

如何在SwiftUI列表中加载元组数组

  •  -1
  • fs_tigre  · 技术社区  · 3 年前

    以下代码产生错误 Type cannot conform to 'Hashable' .

    如何将元组数组加载到SwiftUI列表?

    密码

    import SwiftUI
    struct TestingGeneral: View {
    
        let users: [(name: String, age: Double)] = [
            ("Jeff", 25),
            ("Nathan", 18)
        ]
       
        var body: some View {
            VStack{
                List {
                    ForEach(users, id: \.self) { user in
                        Text(user.name)
                        Text("\(user.age)")
                    }
                }
            }
        }
    }
    

    错误

    类型“(名称:String,年龄:Double)”不能符合“Hashable”

    1 回复  |  直到 3 年前
        1
  •  1
  •   lorem ipsum    3 年前

    使用 self 在一个 ForEach 与SwiftUI不太兼容

    ForEach(users, id: \.self) { user in
    

    您应该始终有一个唯一的变量。SwiftUI就是关于身份的。

    ForEach(users, id: \.name) { user in
    

    查看#wwdc21中的解密SwiftUI https://developer.apple.com/wwdc21/10022