Set

Set is a collection which stores values of the same type, but just a single copy of it. There is no order in this collection. The set can be used instead of an array, if the item order is not taken into account. The benefit when using set is that each value will appear only once.

The types which can be stored in a set must be hashable (must implement the Hashable protocol—for more information, read about protocols later in this chapter). A hash value (we can think of a corresponding int) can be calculated for each hashable object. For equal objects, the same hash value is assigned.

A hash value shouldn't be stored, because it might differ between different executions of a program.

For example:

let a = 5let b = 5 if a.hashValue == b.hashValue ...

Get Learn Swift by Building Applications 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.