Equatable

Some of the simplest code compares two integers with the == operator:

let a = 5 let b = 5

a == b // true

You can do the same thing with strings:

let swiftA = "Swift" let swiftB = "Swift"

swiftA == swiftB // true

But you can’t use == on any type. Suppose you wrote a struct that represents a team’s record and wanted to determine if two records were equal:

struct Record { var wins: Int var losses: Int

}

let recordA = Record(wins: 10, losses: 5) let recordB = Record(wins: 10, losses: 5)

recordA == recordB // Build error!

You can’t apply the == operator to the struct you just defined. But the use of the equality operator isn’t simply “magic” reserved for standard Swift types like Int and String; they’re structs, just like Record. This means you can extend the use of this

operator to your own code!

Both Int and String conform to the Equatable protocol from the the standard library that defines a single function:

protocol Equatable {

static func ==(lhs: Self, rhs: Self) -> Bool

}

You can apply this protocol to Record like so:

extension Record: Equatable {

static func ==(lhs: Record, rhs: Record) -> Bool { return lhs.wins == rhs.wins &&

lhs.losses == rhs.losses

}

}

Here, you’re defining (or overloading) the == operator for comparing two Record instances. In this case, two records are equal if they have the same number of wins and losses.

Now, you’re able to use the == operator to compare two Record types, just like you can with String or Int:

recordA == recordB // true

results matching ""

    No results matching ""