[英]How to create a collection of Identifiable objects similar to Set?
Set
非常适合避免重复、联合和其他操作。 但是,对象不应该是Hashable
,因为 object 中的更改将导致Set
中的重复。
SwiftUI 中有一个List
使用Identifiable
协议来管理集合,但面向视图。 是否有以相同方式运作的集合?
比如下面的object,我想管理一个集合:
struct Parcel: Identifiable, Hashable {
let id: String
var location: Int?
}
var item = Parcel(id: "123")
var list: Set<Parcel> = [item]
后来,我改变了项目的位置并更新了列表:
item.location = 33435
list.update(with: item)
由于 hash 已更改,这会将重复项添加到列表中,但由于它具有相同的标识符,因此不打算这样做。 有没有一种处理可Identifiable
对象集合的好方法?
仅使用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.