Search code examples
swiftswiftuiswift5

Swift 5.+ - Making a class hashable?


I'm very new to swift so please pardon any obvious misunderstandings. I've tried to research with no good answer.

I have a NavigationView with the following iteration

ForEach(listOfStuff, id: \.self)

The listOfStuff is defined as a struct conforming to Hashable and everything works just fine.

I wanted to change the struct to a class, and can't figure out how to make the class Hashable so that the \.self works (it keeps complaining that the class has to be Hashable)

Examples are old or keep talking about struct. I don't even know if I can even use a class in the ForEach? What do I do?

Thank you


Solution

  • Here is an example for using class-based model in the described use-case. Tested with Xcode 11.4

    class Stuff: Hashable, Equatable {
        static func == (lhs: Stuff, rhs: Stuff) -> Bool {
            lhs.title == rhs.title
        }
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(title)
        }
    
        var title: String = ""
    }
    
    struct StaffView: View {
        let listOfStaff: [Stuff]
    
        var body: some View {
            ScrollView {
                ForEach(listOfStaff, id: \.self) { stuff in
                    Text(stuff.title)
                }
            }
        }
    }