NEW! Master Swift design patterns with my latest book! >>

How to create hash values from objects using Hasher

Paul Hudson       @twostraws

Hash values are an invaluable way of identifying data uniquely, and any type that conforms to the Hashable protocol can be used to create all or part of a hash value by using the Hasher struct.

To use this, create an instance of Hasher, provide it with whatever objects you want to hash, then call finalize() to generate the final value as an integer. For example:

struct iPad: Hashable {
    var serialNumber: String
    var capacity: Int
}

let first = iPad(serialNumber: "12345", capacity: 128)
let second = iPad(serialNumber: "abcde", capacity: 512)

var hasher = Hasher()
hasher.combine(first)
hasher.combine(second)
let hash = hasher.finalize()

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>