简体   繁体   中英

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

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM