0Pricing
Swift Academy · Lesson

Comparable and Sorting

Define ordering with < for sorting.

What Is Comparable?

Comparable gives a type ordering operators: <, <=, >, >=. Conforming lets you call sorted(), min(), and max() directly.

Conforming with <

You only implement <; the rest are derived. (Equatable is also required.)

struct Version: Comparable {
    let major: Int
    static func < (l: Version, r: Version) -> Bool { l.major < r.major }
}
print(Version(major: 1) < Version(major: 2))  // true

All lessons in this course

  1. Synthesized Equatable
  2. Hashable and hash(into:)
  3. Comparable and Sorting
  4. Custom Equality Semantics
← Back to Swift Academy