Home > Net >  How to load an array of tuples in a SwiftUI List
How to load an array of tuples in a SwiftUI List

Time:01-03

The following code produces the error Type cannot conform to 'Hashable'.

How can I load an array of tuples to a SwiftUI List?

Code

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)")
                }
            }
        }
    }
}

Error

Type '(name: String, age: Double)' cannot conform to 'Hashable'

CodePudding user response:

Using self in a ForEach is not very compatible with SwiftUI

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

You should always have a unique variable. SwiftUI is all about identity.

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

Check out Demystify SwiftUI from #wwdc21 https://developer.apple.com/wwdc21/10022

  • Related