一个 Set
非常适合避免重复、联合和其他操作。但是,对象不应该是 Hashable
因为对象中的更改会导致 Set
中的重复项.
有一个List
在使用 Identifiable
的 SwiftUI 中管理集合的协议(protocol),但面向 View 。是否有以相同方式运作的集合?
例如,对于以下对象,我想管理一个集合:
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)
由于散列已更改,这会向列表中添加一个重复项,但由于它具有相同的标识符,因此并非有意为之。有没有好办法处理
Identifiable
的集合对象?
最佳答案
实现 hash(into)
(和 ==)仅使用 id
为您的类型属性(property)
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: Parcel, rhs: Parcel) -> Bool {
lhs.id == rhs.id
}
关于arrays - 如何创建类似于 Set 的 Identifiable 对象的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61892203/