Menu
Coddy logo textTech

Comparable

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 39 of 57.

Comparable gives a type the <, <=, > and >= operators. You implement only <; Swift derives the rest. Comparable types can be sorted with sorted() and used with min() and max():

struct Version: Comparable {
    let major: Int, minor: Int

    static func < (lhs: Version, rhs: Version) -> Bool {
        (lhs.major, lhs.minor) < (rhs.major, rhs.minor)
    }
}

let versions = [Version(major: 2, minor: 1), Version(major: 1, minor: 9), Version(major: 2, minor: 0)]
let newest = versions.max()!
print("\(newest.major).\(newest.minor)")
print(versions.sorted().map { "\($0.major).\($0.minor)" })

Output:

2.1
["1.9", "2.0", "2.1"]

Comparing tuples compares their parts in order, which makes multi-key comparisons short. Here tasks sort by priority first and then by name:

struct Task: Comparable {
    let priority: Int
    let name: String

    static func < (lhs: Task, rhs: Task) -> Bool {
        (lhs.priority, lhs.name) < (rhs.priority, rhs.name)
    }
}

let tasks = [Task(priority: 2, name: "email"), Task(priority: 1, name: "fix"), Task(priority: 2, name: "call")]
print(tasks.sorted().map { $0.name })

Output:

["fix", "call", "email"]

Enums without associated values can conform to Comparable without writing <: the cases compare in the order they are declared:

enum Priority: Comparable {
    case low, medium, high
}

print(Priority.low < Priority.high)
print([Priority.high, .low, .medium].sorted())

Output:

true
[main.Priority.low, main.Priority.medium, main.Priority.high]

sorted(by:) sorts with any rule for one call, while Comparable defines the type's natural order that sorted(), min() and max() use everywhere:

struct Task: Comparable {
    let priority: Int
    let name: String
    static func < (lhs: Task, rhs: Task) -> Bool { lhs.priority < rhs.priority }
}

let tasks = [Task(priority: 3, name: "c"), Task(priority: 1, name: "a")]
print(tasks.sorted().map { $0.name })
print(tasks.sorted(by: >).map { $0.name })

Output:

["a", "c"]
["c", "a"]
challenge icon

Challenge

Easy

Make Runner (name and finishing time as minutes, seconds) conform to Comparable, where a faster time is smaller and equal times are ordered by name. Complete podium(_:), which sorts the runners with sorted() and returns 1. Ada 20:05 lines for the first three (fewer if there are fewer runners), with seconds padded to two digits.

The supplied code reads lines name,mm:ss and prints each returned line.

Your code goes in Runner.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let runners = input.map { line -> Runner in
    let p = line.split(separator: ",").map(String.init)
    let t = p[1].split(separator: ":").map { Int($0)! }
    return Runner(name: p[0], minutes: t[0], seconds: t[1])
}
for line in podium(runners) { print(line) }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground