Tru*_*an1 7 arrays uniqueidentifier swift
ASet
非常适合避免重复、并集和其他操作。但是,对象不应该这样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]
Run Code Online (Sandbox Code Playgroud)
后来,我改变了项目的位置并更新了列表:
item.location = 33435
list.update(with: item)
Run Code Online (Sandbox Code Playgroud)
由于散列已更改,这会向列表中添加重复的项目,但这并不是有意的,因为它具有相同的标识符。有没有好的方法来处理Identifiable
对象集合?
仅使用属性为您的类型实现hash(into)
(和 ==)id
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: Parcel, rhs: Parcel) -> Bool {
lhs.id == rhs.id
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
594 次 |
最近记录: |