如何创建类似于 Set 的可识别对象集合?

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

A Set 非常适合避免重复、联合和其他操作。但是,对象不应该是 Hashable,因为对象的更改会导致 Set 中出现重复。

SwiftUI 中有一个 List 使用 Identifiable 协议来管理集合,但面向视图。是否有以相同方式操作的集合?

例如,对于以下对象,我想管理一个集合:

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 个对象的集合?

仅使用 id 属性

为您的类型实施 hash(into)(和 ==)
func hash(into hasher: inout Hasher) { 
    hasher.combine(id) 
}

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