swift - 如何使具有可选属性的自定义类符合 "hashable"协议(protocol)

标签 swift option-type hashable

假设我有一个基类“Person”,我想将其添加到一个集合(列表)中,因此需要符合 Hashable 和 Equatable:

class Person : Equatable, Hashable {
let firstName: String
let lastName: String
var nickname: String?
let dateOfBirth: NSDate
var hashValue: Int {
    if let nickname = nickname {
        return firstName.hashValue ^
               lastName.hashValue ^
               nickname.hashValue ^
               dateOfBirth.hashValue
    } else {
        return firstName.hashValue ^
               lastName.hashValue ^
               dateOfBirth.hashValue
    }

}

init (firstName: String, lastName: String, nickname: String, bornOn dateOfBirth: NSDate) {
    self.firstName = firstName
    self.lastName  = lastName
    self.nickname = nickname
    self.dateOfBirth = dateOfBirth
    }
}

func ==(lhs: Person, rhs: Person) -> Bool {
    return
        lhs.firstName   == rhs.firstName    &&
        lhs.lastName    == rhs.lastName     &&
        lhs.nickname    == rhs.nickname     &&
        lhs.dateOfBirth == rhs.dateOfBirth
}

此类只有一个可选属性,这使得在创建哈希值时对可选属性的处理相当合理。如果有 2 个或更多可选属性怎么办?我可以看到这很快就会失控。

在使对象符合可散列协议(protocol)时,通常如何处理可选属性?

最佳答案

哈希值的计算不必基于所有属性。事实上,它不需要基于任何。你可以简单地返回一个硬编码的数字,但你不应该这样做。

简单地返回一个或多个非可选属性的哈希值。

唯一的规则是比较相等的两个对象也必须返回相同的散列值。但是不要求具有相同散列值的两个对象比较相等。

关于swift - 如何使具有可选属性的自定义类符合 "hashable"协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754595/

相关文章:

ios - 如何从 JSON 数据响应中获取 UIImage?

ios - 在scrollView ios swift中放大UIView

在 guard 语句中快速使用 break

swift - Swift 哈希的缓存结果(到 :) Hashable protocol requirement

python - 是什么让用户定义的类不可散列?

swift - swift hashable 协议(protocol)哈希函数是否需要返回唯一值?

ios - 如何将 UIPanGestureRecognizer 添加到在 CAShapLayer 上绘制的形状 - swift?

ios - 如何让 iOS 应用程序在 Swift 中永远在后台运行?

java-8 - 如何获取可选列表中特定索引处的元素?

java-8 - 使用选项重写 if else null 检查