Sets in Swift

swift sets

Sets are one of Swift’s collection types. A set stores an amount of unique values, that have no particular order. You can imagine a set to be like a box of billiard balls: They are all unique in terms of color and number, but they don’t have a certain order inside the box.

Hint: This post is using Swift 4 and Xcode 10

Creating sets

Creating a set is very straightforward:

In this example, a set called setA  of strings has been created. It stores the values a, b  and c. In contrast to an array, the elements are not ordered. By using type interference, the set can also be created like this:

It’s also possible to use the initialiser of the set type:

Like an array, a set is not mutable, if it’s declared as a constant by using let. For mutable sets, you can use the keyword var:

We will learn more about mutable sets later on.

Accessing the values of a set

You can access the values of a set by using a loop:

Note that the order of the values in the loop can be different every time you run the code. From the outside it looks like they the values are picked randomly.

Analysing sets

First of all, you can check whether a set is empty:

Also the number of elements of a set can be checked:

Both of these operations are also available for arrays. More typical for a set is the question, whether a certain element is a member of a set. For that, you can use the method contains:

Adding and removing values from a set

Mutable sets can be changed. You can add and remove values:

Since the values of a set are unique, a value can only be added once to the same set. The insert method can be called with the same values multiple times, but the set won’t change:

As before, the order of the output can be different every time you run the code since sets are not ordered.

Comparing sets

Sets can be compared. Obviously, comparing the equality of two sets is possible:

In this case, the sets are equal.

There is no useful definition for a smaller and bigger comparison of two sets, but you can check whether a set is a subset of another set:

It’s also possible to check whether it’s a strict subset. In that case, it has to be a subset but must not be equal:

The opposite principle is a superset:

Two sets are disjoint, if they don’t have any element in common:

Combining sets

You can combine two sets to create a new one. A union of two sets contains all elements from both sets:

An intersection on the other hand contains only the elements, that are in both sets:

Using sets with custom types

Of course you can also store values of your own type in a set. This type could be for example a struct or a class. However, in order for the set to work properly, this type has to conform to the hashable protocol.

References:

Title image: @ LaineN / shutterstock.com