A type that can be compared using the relational operators
- Xcode 6.0.1+
Comparable protocol is used for types that have an inherent order, such as numbers and strings. Many types in the standard library already conform to the
Comparable protocol. Add
Comparable conformance to your own custom types when you want to be able to compare instances using relational operators or use standard library methods that are designed for
The most familiar use of relational operators is to compare numbers, as in the following example:
You can use special versions of some sequence and collection operations when working with a
Comparable type. For example, if your array’s elements conform to
Comparable, you can call the
sort() method without using arguments to sort the elements of your array in ascending order.
Conforming to the Comparable Protocol
Types with Comparable conformance implement the less-than operator (
<) and the equal-to operator (
==). These two operations impose a strict total order on the values of a type, in which exactly one of the following must be true for any two values
a == b
a < b
b < a
In addition, the following conditions must hold:
a < ais always
a < bimplies
!(b < a)(Asymmetry)
a < band
b < cimplies
a < c(Transitivity)
Comparable conformance to your custom types, define the
== operators as static methods of your types. The
== operator is a requirement of the
Equatable protocol, which
Comparable extends—see that protocol’s documentation for more information about equality in Swift. Because default implementations of the remainder of the relational operators are provided by the standard library, you’ll be able to use
>= with instances of your type without any further code.
As an example, here’s an implementation of a
Date structure that stores the year, month, and day of a date:
Comparable conformance to
Date, first declare conformance to
Comparable and implement the
< operator function.
This function uses the least specific nonmatching property of the date to determine the result of the comparison. For example, if the two
year properties are equal but the two
month properties are not, the date with the lesser value for
month is the lesser of the two dates.
Next, implement the
== operator function, the requirement inherited from the
Date instances are equal if each of their corresponding properties is equal.
Date conforms to
Comparable, you can compare instances of the type with any of the relational operators. The following example compares the date of the first moon landing with the release of David Bowie’s song “Space Oddity”:
Note that the
> operator provided by the standard library is used in this example, not the
< operator implemented above.