如何创建一个类似于Set的Identifiable对象集合?

问题描述 投票:3回答:1

A Set 是很好的避免重复、联合和其他操作。然而,对象不应该是 Hashable 因为对象的变化将导致重复的对象。Set.

有一个 List 在SwiftUI中使用 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 对象?

arrays swift uniqueidentifier
1个回答
1
投票

实现 hash(into) (和==),您的类型只需使用 id 财产

func hash(into hasher: inout Hasher) { 
    hasher.combine(id) 
}

static func == (lhs: Parcel, rhs: Parcel) -> Bool {
    lhs.id == rhs.id
}
© www.soinside.com 2019 - 2024. All rights reserved.