Swift Equatable & Comparable

Swift Equatable and Comparable

To make your custom types feel like first-class citizens in Swift, they need to support basic operators like == and <.

Swift uses protocols to define these behaviors.

By conforming your custom structs and classes to the Equatable and Comparable protocols, you unlock immense power and flexibility.


The Equatable Protocol

Types that conform to Equatable can be compared for equality using the == operator or inequality using !=.

For simple structs and enums, Swift compiler is smart enough to synthesize the == logic for you automatically, as long as all properties inside the struct are also Equatable (like Ints and Strings)!

Automatic Equatable:

// By simply appending : Equatable, Swift does the hard work
struct Point: Equatable {
    var x: Int
    var y: Int
}

let point1 = Point(x: 5, y: 10) let point2 = Point(x: 5, y: 10)

// Now we can check if they are identical! if point1 == point2 { print("The points are exactly the same!") }


The Comparable Protocol

If you want to sort an array of your custom types or compare them using <, >, <=, or >=, you must conform to the Comparable protocol.

Unlike Equatable, Swift cannot automatically guess how you want to sort your custom objects. You must explicitly write a function that dictates the rules.

You do this by implementing the static < method.

Custom Comparable:

struct Player: Comparable {
    var name: String
    var score: Int
    // We define what makes one player "less than" another
    static func < (lhs: Player, rhs: Player) -> Bool {
        return lhs.score < rhs.score
    }
}

let playerA = Player(name: "Alice", score: 150) let playerB = Player(name: "Bob", score: 200)

if playerA < playerB { print("\(playerB.name) is winning!") }


Sorting Made Easy

Once your custom type conforms to Comparable, you gain access to powerful built-in sequence methods.

For instance, you can take an entire array of Player objects and simply call .sorted() on it. Swift will automatically use your custom < logic to sort the entire array from lowest score to highest score!


Exercise

Which static method must you implement to conform to the `Comparable` protocol?