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?

In fact, you have been doing this with Swift’s basic types throughout this 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 here that values can and should be comparable. We intuitively want to know how one integer compares ...

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.