Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Conform to Comparable in Swift
Written by Team Kodeco

When working with custom types in Swift, you may want to allow for comparison operators like < and > to be used on instances of that type. To do this, you can conform to the Comparable protocol for your custom type.

The Comparable protocol requires that you implement a single method called < which takes two instances of your custom type and returns a Boolean indicating whether the first instance is less than the second.

Here’s an example of how you might conform to the Comparable protocol for a custom Point class:

class Point: Comparable {
  var x: Int
  var y: Int

  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }

  static func < (lhs: Point, rhs: Point) -> Bool {
    if lhs.x < rhs.x {
      return true
    } else if lhs.x == rhs.x {
      return lhs.y < rhs.y
    } else {
      return false
    }
  }
  // Swift requires that you also implement ==
  static func == (lhs: Point, rhs: Point) -> Bool {
    return lhs.x == rhs.x && lhs.y == rhs.y
  }
}

In this example, you define a Point class with x and y properties. You then conform to the Comparable protocol by defining a static function called < that takes two Point parameters and returns a Bool indicating whether the x value of the first Point is less than the x value of the second Point. If the x values are equal, it compares the y value.

Now you can use comparison operators on Point instances:

let point1 = Point(x: 1, y: 2)
let point2 = Point(x: 3, y: 4)
let point3 = Point(x:1, y:3)
print(point1 < point2) // true
print(point1 > point2) // false
print(point1 == point3) // false

It’s important to note that, conforming to the Comparable protocol allows you to use all the comparison operators (<,>,<=,>=) on custom types.

© 2024 Kodeco Inc.