arrays - 如何创建类似于 Set 的 Identifiable 对象的集合?

标签 arrays swift uniqueidentifier

一个 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/

相关文章:

string - 如何使用整数唯一标识一组字符串

Java数组越界-数独

swift - 简单的 URLSession 示例总是因错误而失败

c - 无需预洗牌即可生成(非常)大的非重复整数序列

ios - [UIDevice currentDevice].identifierForVendor.UUIDString 返回全零

ios - 通知中心addObserver

c++ - 在包含数组中存在的所有元素的数组中找到最短的范围

arrays - 使用静态范围最小查询维护的数组中单个更改的复杂性

javascript - 将 JS 对象(键和值)展平为单个深度数组的最佳方法

iOS( swift ): Core data fetching with relationships