[英]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.