ios - 包含结构的数组的哈希值

标签 ios arrays swift hash

我有一个名为 Survey 的结构。它符合 EquatableHashable 协议(protocol)。

import Foundation

public struct Survey {
    public let id: String
    public let createdAt: Date
    public let updatedAt: Date
    public let title: String
    public let type: String
}

extension Survey: Equatable { }

public func ==(lhs: Survey, rhs: Survey) -> Bool {
    return lhs.id == rhs.id && lhs.createdAt == rhs.createdAt && lhs.updatedAt == rhs.updatedAt && lhs.title == rhs.title && lhs.type == rhs.type
}

extension Survey: Hashable {
    public var hashValue: Int {
        return id.hashValue ^ createdAt.hashValue ^ updatedAt.hashValue ^ title.hashValue ^ type.hashValue
    }
}

我可以获得单个 Survey 对象的哈希值。

但是如何获取包含多个 Survey 对象的数组的哈希值?

最佳答案

也许是这样的?

extension Array: Hashable where Iterator.Element: Hashable {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}

自定义哈希值就是你定义的值

*编辑:如果您只想将 Hashable 用于 Survey 数组

,这也适用
extension Array: Hashable where Element == Survey {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}

关于ios - 包含结构的数组的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061041/

相关文章:

java - 为什么我只能在 while 循环之外获取数组的最后一个元素

arrays - 如何在 ruby​​ 数组中仅添加正数?

ios - 无法找到在 Swift 中使用 Google 客户端库的用户的 serverAuthCode

ios - iPhone - 自动调整 UIWebView 内容不适合框架

ios - 没有状态栏的导航栏与iOS 11中的安全区域重叠

ios - Realm Swift - 保存对另一个对象的引用

swift - 更新到 Xcode 11 后,CGAffineTransform 翻译在标签栏上不起作用

ios - 自动调整表格 View 单元格内的自动调整表格 View 大小

c++ - 使用数组中的值,包含多个 vector

ios - 通过 Segue 传递 indexPath