Hashing McGlashing
Published on Dec 10, 2019Hashing McGlashing β SwiftMoji Entry #11
Conformance to the Hashable protocol allows each π€ in a set to be uniquely identified as long as one property is distinct. This unique ID called a hash value can be used to search a Set for a member in constant time (O(1)). This efficiency is a result of the contains(_:) method having direct access to each corresponding memory address in a hash table, instead of being required to iterate over each Element as in Arrays. As of Swift 4.2, the implementation of the underlying hashValue computed property is automatically provided by passing a valueβs properties into the Hasher structβs combine(_:) method and then using the finalize() method to obtain the Int.
struct π€: Hashable {
let name: String
let age: Int
let apartmentNumber: Int
let ownsPets: Bool
}
typealias π© = String
struct πͺ {
var contents = [π©]()
}
struct π’ {
let residents: Set<π€>
var mailbox = πͺ()
}
var π = π’(residents: [
π€(name: "Nicolas", age: 21, apartmentNumber: 315, ownsPets: false),
π€(name: "Sam McGlashing", age: 50, apartmentNumber: 118, ownsPets: true),
π€(name: "Jonah", age: 35, apartmentNumber: 220, ownsPets: true),
π€(name: "Sam McGlashing", age: 25, apartmentNumber: 305, ownsPets: true)
])
let π¨πΌβ𦳠= π€(name: "Sam McGlashing", age: 50, apartmentNumber: 118, ownsPets: true)
let π = "Hello Sam!"
if π .residents.contains(π¨πΌβπ¦³) {
π .mailbox.contents.append(π)
}
Tagged with: