Swift, how to implement Hashable protocol based on object reference?

前端 未结 5 1047
野趣味
野趣味 2020-12-29 04:16

I\'ve started to learn swift after Java. In Java I can use any object as a key for HashSet, cause it has default hashCode and equals based on objec

5条回答
  •  有刺的猬
    2020-12-29 04:46

    Swift 5 barebones

    For a barebones implementation of making a class hashable, we simply must conform to both the Equatable and Hashable protocols. And if we know our object well, we can determine which property or properties to use to make it equatable and hashable.

    class CustomClass: Equatable, Hashable {
        let userId: String
        let name: String
        let count: Int
        
        init(userId: String, name: String, count: Int) {
            self.userId = userId
            self.name = name
            self.count = count
        }
        
        /* Equatable protocol simply means establishing a predicate to
           determine if two instances of the same type are equal or unequal based
           on what we consider equal and unequal. In this class, userId makes
           the most sense so if we were to compare two instances (left-hand-side
           versus right-hand-side), we would compare their userId values. When
           it comes time to compare these objects with each other, the machine
           will look for this function and use it to make that determination. */
        static func == (lhs: CustomClass, rhs: CustomClass) -> Bool {
            return lhs.userId == rhs.userId
        }
        
        /* Hashable protocol is similar to Equatable in that it requires us to
           establish a predicate to determine if two instances of the same
           type are equal or unequal, again based on what we consider equal and
           unequal. But in this protocol we must feed that property into a
           function which will produce the object's hash value. And again, userId
           makes the most sense because each instance carries a unique value. If
           userId was not unique, we could combine multiple properties to
           generate a unique hash. */
        func hash(into hasher: inout Hasher) {
            hasher.combine(userId)
            //hasher.combine(name) if userId was not unique, we could have added this
        }
    }
    

提交回复
热议问题