Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to load an array of tuples in a SwiftUI List

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading