25 Equatable and Comparable

Much of programming depends on comparing values. It is important to know whether two values are equal or, if not, how one value compares to another: is this value less than or greater than that value?

It is good practice to have your custom value types know how to compare themselves to other instances. In fact, you have been doing this with Swift’s basic types throughout the book. Does this string equal another string? Is this integer smaller than that integer? All of Swift’s basic types know how to compare themselves to other instances of the same type. Why?

The answer is closely related to the purpose of value types. Instances of these types represent specific values. There is an intrinsic expectation ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.