用 hash(into:) 计算哈希

版本新特性 / Swift 4.2

// *** 以前 ***
struct PointOld: Hashable {
    let x: Int
    let y: Int

    // 混合方式由作者自己发明,质量差的会让 Set 退化成线性查找的列表
    var hashValue: Int { return x.hashValue ^ y.hashValue }
}

// *** 在 4.2 版本中 ***
struct Point: Hashable {
    let x: Int
    let y: Int

    func hash(into hasher: inout Hasher) {
        hasher.combine(x)      // 字段被送入标准哈希器
        hasher.combine(y)
    }
}

// hashValue 已弃用;哈希器每次运行程序时都使用新的种子,
// 所以哈希值不得存入磁盘,也不得通过网络发送
var hasher = Hasher()
hasher.combine(Point(x: 1, y: 2))
print(hasher.finalize())