Building Equality Functionality Into Your Own Types - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.13 Building Equality Functionality Into Your Own Types

Problem

You have your own structs and classes and you want to build equality-checking functionality into them.

Solution

Build your equality functionality into the protocols to which your types conform. This is the way to go!

Discussion

Let me give you an example. Let’s say that we have a protocol called Named:

protocol Named{

var name: String {get}

}

We can build the equality functionality into this protocol. We can check the name property and if the name is the same on both sides, then we are equal.

func ==(lhs : Named, rhs: Named) -> Bool{

return lhs.name == rhs.name

}

Now let’s define two types, a car and a motorcycle, and make them conform to this protocol:

struct Car{}

struct Motorcycle{}

extension Car : Named{

var name: String{

return "Car"

}

}

extension Motorcycle : Named{

var name: String{

return "Motorcycle"

}

}

That was it, really. You can see that I didn’t have to build the equality functionality into Car and into Motorcycle separately. I built it into the protocol to which both types conform. And then we can use it like so:

func example1(){

let v1: Named = Car()

let v2: Named = Motorcycle()

if v1 == v2{

print("They are equal")

} else {

print("They are not equal")

}

}

This example will say that the two constants are not equal because one is a car and the other one is a motorcycle, but what if we compared two cars?

func example2(){

let v1: Named = Car()

let v2: Named = Car()

if v1 == v2{

print("They are equal")

} else {

print("They are not equal")

}

}

Bingo. Now they are equal. So instead of building the equality functionality into your types, build them into the protocols that your types conform to and you are good to go.

See Also