In this section, we will show how we can conform to the Equatable
protocol using extensions. When a type conforms to the Equatable
protocol, we can use the equal-to (==
) operator to compare for equality and the not-equal-to (!=
) operator to compare for inequality.
Note
If you will be comparing instances of a custom type, it is a good idea to have that type conform to the Equatable
protocol because it makes comparing instances very easy.
Let's start off by creating the type that we will compare. We will name this type Place
:
struct Place { let id: String let latitude: Double let longitude: Double }
In the Place
type, we have three properties that represent the ID of the place and the latitude and longitude coordinates for its location. If there are two instances of the Place
type that have the same ID and coordinates, then they would be considered the same place.
To implement the Equatable
protocol, we could create a global function. However, that...