Skip to content

Comparable enum

1 min read

From Swift 5.3 and later, enums can be comparable. We can compare two cases from the enum with >, < and similar.

enum Sizes: Comparable {
    case S
    case M
    case L
}

let first = Sizes.S
let second = Sizes.L

print(first < second)
// will print true, S comes before L in the enum case list

Enums with associated values can also be comparable.

enum OrderStatus: Comparable {
    case purchased
    case readyToShip
    case shipping(progress: Int)
    case shippingComplete
}

let orderStatusList = [shippingComplete, readyToShip, shipping(progress: 0.5), shipping(progress: 0.3), purchased]
let sortedByStatus = orderStatusList.sorted()
print(sortedByStatus)
// purchased, readyToShip, shipping(progress: 0.3), shipping(progress: 0.5), shippingComplete

In the above example, array will be sorted similar with the enum case list. But shipping(progress: 0.5) will consider to be higher than shipping(progress: 0.3).

Refrence
Synthesized Comparable conformance for enum types


Share this post on:

Previous Post
Fork한 Repository Sync하기 (동기화하기)
Next Post
How to show build times in Xcode