我有一个名为 Survey
的结构。它符合 Equatable
和 Hashable
协议(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/