Swift World Evolution: SE-0185 Synthesizing Equatable and Hashable Conformance

Peng
SwiftWorld
Published in
2 min readAug 21, 2017
Photo by Stacy Wyss on Unsplash

Swift World Evolution: SE-0185 Synthesizing Equatable and Hashable Conformance Swift is evolving. Swift 4 is just in sight and Swift 5 begins. I start this new series to keep watching its evolution. This is not detailed but simple explanation for proposal. SE-0185 has just got accepted. So let’s get started with it.

SE-0185 is about Equatable and Hashable. I have published a series to explain Equatable, Comparable and Hashable as shown below.

Swift World: Equatable, Comparable and Hashable Part 1

Swift World: Equatable, Comparable and Hashable Part 2

Swift World: Equatable, Comparable and Hashable Part 3

Simply speaking, SE-0185 proposes to synthesize codes to conform to Equatable and Hashable automatically by compiler instead of manually by developer.

We will start with a simple Struct Superhero with two properties: name and real name.

To do equality test with ==, conformance to Equatable is required like following code snippet. Let’s assume Superheroes are equal when their names and real names are equal respectively.

An obvious shortage is that any change of the property in a type will lead to change in Equatable conformance. This will increase maintenance cost and potential risk by manual update. What if we add birth date or age to Superhero? We need to update this conformance correspondingly.

Hashable is in the same situation especially a high-quality hash function is required for conformance.

The solution in this proposal is

a type synthesize conformance to Equatable/Hashable if all of its members are Equatable/Hashable.

For example in our Superhero, because name and realName are both String, the conformance to Equatable is synthesized by compiler. If we give our own implementation, it will be overrode by ours.

The real world is more complicated. The proposal describes details for different types and different conditions. Please get the details from SE-0185 and the thread swift-evolution Universal Equatability, Hashability, and Comparability. We will come back when this proposal comes true.

Thanks for your time. Please clap to get this article seen by more people. Please follow me and Swift World by clicking Follow. Recommendations are highly welcomed for Swift World This Week.

Peng is a passionate iOS developer, blogger and open source contributor. Talk to him by nilstack(Twitter)/guoleii@gmail.com/nilstack(GitHub)/Peng(Linkedin).

--

--

Peng
SwiftWorld

Engineers are the artists of our generation.