A set is an unordered collection of unique elements. It can very efficiently add, remove, or check if it contains a specific element (on average O(1), meaning it takes the same time regardless of the size of the set), in contrast to an unsorted array, where these operations take O(n) (the array may need to access and/or move most of its element).

Sets can be used for tracking which part of a custom view should be hidden, like which parts of an outline view are collapsed. When displaying the view, you would only show the children of those nodes which are not in the collapsed set. So, you are in a sense adding a Bool property to types you do not control. Sets can also be used for removing duplicates; you just add a sequence to an empty set and all duplicates will be gone.

Have a look at the following diagram to get a view on sets:

Sets

All types used in a set have to conform to the Hashable protocol:

Sets

A lot of other types conform to Hashable as well (https://developer.apple.com/documentation/swift/hashable#adopted-by).

The most common method of removing duplicates from a sequence is to just add the entire sequence to a set, and then create a new sequence from the set. However, this might re-order the remaining elements. Here, we will use filter to keep the original order, and use a set to keep track of which values are already in the sequence.

By adding the method as an extension to Sequence, it can be used by any collection type, including Array, Dictionary, and Set (though it would be rather pointless to use it on dictionaries and sets, as they are already duplicate-free).

To use an Xcode playground to create a method which removes duplicates from a sequence while preserving the order of the remaining values.