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?
Set<Car>
and you addHonda
andHonda
well typically the set wouldn't allow that but you might need to tell thatSet<Car>
that the second Honda only has 3x tires instead of 4. On the surface, it looks like a duplicate but it's really not. The other option would be to identifyWHY
does it allow duplicates if a hash is changed? Extend that feature and remove the unwanted behavior. – WaterlooList
. – VesicateSet
to offer methods like union, update, insert, but surprised nothing native for this unless I'm missing something. – Vesicatelet ids = items.map(\.id); parcels.filter { !ids.contains($0.id) } + items
where I'd just like to do justitems.union(parcels)
. – VesicateHashable
for your type?func hash(into hasher: inout Hasher) { hasher.combine(id) }
– Chadburn