简体   繁体   English

如何创建类似于 Set 的 Identifiable 对象集合?

[英]How to create a collection of Identifiable objects similar to Set?

A Set is great for avoiding duplicates, unions, and other operations. Set非常适合避免重复、联合和其他操作。 However, objects shouldn't be Hashable because the changes in the object will cause duplicates in a Set .但是,对象不应该是Hashable ,因为 object 中的更改将导致Set中的重复。

There is a List in SwiftUI that uses the Identifiable protocol to manage the collection, but is geared towards views. SwiftUI 中有一个List使用Identifiable协议来管理集合,但面向视图。 Is there collection that operates the same way?是否有以相同方式运作的集合?

For example, for the following object, I'd like to manage a collection:比如下面的object,我想管理一个集合:

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.由于 hash 已更改,这会将重复项添加到列表中,但由于它具有相同的标识符,因此不打算这样做。 Is there a good way to handle a collection of Identifiable objects?有没有一种处理可Identifiable对象集合的好方法?

Implement hash(into) (and ==) for your type using only the id property仅使用id属性为您的类型实现hash(into) (和 ==)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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