swiftswiftui

Purpose of Hashable, when object is identifiable?


I have seen this code in one of Paul Hudson's videos. Only member accessable, but here's the corresponding text: Coding challenge

struct Friend: Hashable, Identifiable, Codable {
    let id: UUID
    /* ... */
}

I know Hashable as an alternative to identifiable, when you want to use the object with a list/ForEach and the object has no ID and you don't want to add it.

What's the purpose of having both (Hashable & Identifiable)?


Solution

  • I would guess Paul Hudson added Hashable as a workaround for the compiler error when doing:

    NavigationLink(value: friend)
    

    But instead he should have done:

    NavigationLink(value: friend.id)
    

    The reason is .navigationDestination should retrieve the friend from the model via its ID to maintain the single source of truth design that SwiftUI uses. I.e. it shouldn't have a copy of the friend in the navigation path which would cause a potential consistency bug.