O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Equatable and Comparable

We are able to compare two value types such as String, Int, and Double, but we cannot compare two custom value types that we have developed. To make our custom value types comparable, we need to implement Equatable and Comparable protocols. Let's first examine an example of equality checking without conforming to protocols:

struct Point {     let x: Double     let y: Double } let firstPoint = Point(x: 3.0, y: 5.5) let secondPoint = Point(x: 7.0, y: 9.5) let isEqual = (firstPoint == secondPoint)

In this example, the compiler will complain that binary operator == cannot be applied to two Point operands. Let's fix this problem by conforming to the Equatable protocol:

struct Point: Equatable {     let x: Double  let y: Double ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required