The next collection type we will look at is a set. Sets differ from arrays in two important ways. The elements in a set are stored unordered, and each unique element is only held once. In this recipe, we will look at how we can create and manipulate sets.
Containing your data with sets
How to do it...
Let's take a look at the following steps:
- First, let's look at how sets only store unique elements:
let fibonacciArray: Array<Int> = [1, 1, 2, 3, 5, 8, 13, 21, 34]
let fibonacciSet: Set<Int> = [1, 1, 2, 3, 5, 8, 13, 21, 34]
print(fibonacciArray.count) // 10
print(fibonacciSet.count) // 9
- Elements can be inserted and removed, and you can check whether a set contains an element using the following:
var...