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)) // trueAll lessons in this course
- Synthesized Equatable
- Hashable and hash(into:)
- Comparable and Sorting
- Custom Equality Semantics