Comparable
Published Aug 29, 2023Updated Sep 9, 2023
Contribute to Docs
The Comparable
protocol in Swift is used to define a sort order for instances of a type. To add Comparable
conformance to custom types, define the <
and ==
operators as static methods of those types.
Syntax
struct StructName: Comparable {
let var: Int
static func < (lhs: StructName, rhs: StructName) -> Bool {
return lhs.var < rhs.var
}
static func == (lhs: StructName, rhs: StructName) -> Bool {
return lhs.var == rhs.var
}
}
In the implementation of the Comparable
protocol of the custom type defined below, the Comparable
keyword is used in the struct
declaration, then static methods for <
and ==
are defined.
Example
struct Building: Comparable {let height: Intstatic func < (lhs: Building, rhs: Building) -> Bool {return lhs.height < rhs.height}static func == (lhs: Building, rhs: Building) -> Bool {return lhs.height == rhs.height}}let eiffelTower = Building(height: 300)let burjKhalifa = Building(height: 828)let sydneyTower = Building(height: 300)
In this example the custom type, Building
, was created with a height
constant, and static methods for the <
and ==
comparison operators were defined. There are three instances of this type: eiffelTower
, burjKhalifa
and sydneyTower
. The example conforms to the Comparable
protocol, allowing each of the instances to be compared:
print(eiffelTower < burjKhalifa) // trueprint(eiffelTower > sydneyTower) // falseprint(sydneyTower == burjKhalifa) // falseprint(sydneyTower != eiffelTower) // false
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.