美文网首页
2022-09-16

2022-09-16

作者: 时间戳 | 来源:发表于2016-08-23 17:51 被阅读36次

    swift使用对象类型作为Dictionary的key

    使用值类型作为Dictionary的key, 如果使用引用类型,引用类型的修改会导致key的修改
    作为key的类型要遵循 Hashable, Equatable 两个协议

    struct Account {
    var type: Int
    var alias: String
    var createAt: Double

    // 减少hash碰撞
    let INT_BIT = (Int)(CHAR_BIT) * MemoryLayout<Int>.size
    func bitwiseRotate(value: Int, bits: Int) -> Int {
        return (value << bits) | (value >> (INT_BIT - bits))
    }
    

    }

    extension Account: Hashable, Equatable {
    var hashValue: Int {
    return bitwiseRotate(value: type.hashValue, bits: 10) ^ alias.hashValue ^ createAt.hashValue
    }

    static func == (lhs: Account, rhs: Account) -> Bool {
        return lhs.alias == rhs.alias && lhs.type == rhs.type && lhs.createAt == rhs.createAt
    }
    

    }

    相关文章

      网友评论

          本文标题:2022-09-16

          本文链接:https://www.haomeiwen.com/subject/sxlnsttx.html