How to create a collection of Identifiable objects similar to Set?

Viewed 340

A Set is great for avoiding duplicates, unions, and other operations. However, objects shouldn't be Hashable because the changes in the object will cause duplicates in a Set.

There is a List in SwiftUI that uses the Identifiable protocol to manage the collection, but is geared towards views. Is there collection that operates the same way?

For example, for the following object, I'd like to manage a collection:

struct Parcel: Identifiable, Hashable {
    let id: String
    var location: Int?
}

var item = Parcel(id: "123")
var list: Set<Parcel> = [item]

Later, I mutate item's location and update the list:

item.location = 33435
list.update(with: item)

This adds a duplicate item to the list since the hash has changed, but isn't intended since it has the same identifier. Is there a good way to handle a collection of Identifiable objects?

1 Answers

Implement hash(into) (and ==) for your type using only the id property

func hash(into hasher: inout Hasher) { 
    hasher.combine(id) 
}

static func == (lhs: Parcel, rhs: Parcel) -> Bool {
    lhs.id == rhs.id
}
Related