2.2. Sets

A Set in Swift is a similar data structure to an Array with two differences:

  • No item in a set can appear twice. Each item must be unique in a set.

  • A set is not ordered like an array, so we cannot access the items in a set using indices. The items are stored in random positions.

To create a set, we use the following literal:Set<DataType>. For example, the following code creates a new empty set of strings colors:

// Creating an empty set of strings...
var colors = Set<String>()

You can add a new item in a set using insert() function, like:

colors.insert("black")
// prints the current Set...
print(colors)

The print function prints:

["black"]

Let's add a couple more colors:

colors.insert("blue")
colors.insert("black")

// prints the current Set...
print(colors)

Now, if it were an array, the corresponding array would be ["black", "blue", "black"]. However, the above code outputs:

So, we can see that the set colors is not adding black again. It is holding one black and one blue. So, it holds unique elements. Also, the order of the set is not fixed since blue was added after black, but it displays it in the opposite order here.

Now, if you are working with a set where you will not change the elements in the future you should use let to create a set with predefined values.

For example,

Note: you can remove an element from a set by calling remove() function. Try it yourself!

Last updated

Was this helpful?