Start learning free

LESSON 613 OF 640 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in Swift in Swift

Lesson

TL ; DR:

Swift can't compare two objects of your class until you say how. Conform to Equatable by writing ==. For a Set, conform to Hashable and also write hash(into:).


class Time: Hashable {
    ...
    static func == (lhs: Time, rhs: Time) -> Bool {
        return lhs.hour == rhs.hour && lhs.minute == rhs.minute
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(hour)
        hasher.combine(minute)
    }
}


Full lesson:

Write a == b for two Time objects, and the code doesn't compile. A class gets no == by default.

Classes do have ===. It checks identity. It is true only when both variables hold one and the same object.

Equal by value

The protocol Equatable asks for a static func ==. It takes the left and the right object. It returns true when their fields match. Swift then gives you != for free.

Sets need a hash

A Set doesn't compare a new item with every item it holds. That would be slow. It files each object under a number, its hash. Then it compares only objects with the same hash.

Hashable builds on Equatable. It asks for hash(into:), which feeds fields to a Hasher. Feed it the same fields that == compares. inout means the method changes the hasher it gets.

Structs get it for free

A struct whose properties are all Hashable can just say : Hashable. Swift writes both methods for it. A class must write them, as here.


Your task

The Time class keeps an hour and a minute. Write its == and its hash(into:). Two times are equal when the hour and the minute both match.

mainFunction compares three times. Then it puts them in a Set of alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free