Boring guide to Sets in Swift

Jun 20, 20

Set is similar to an array but it does not store duplicate values and set no particular order when storing elements.

  • Set only stores data types that has Hashable. Default data types in Swift such as String, Int, Double, Enums etc are all Hashable.
  • We can also store custom Data Types. But before we try to add them to a Set, we must make sure they conform to Hashable protocol.

Creating an empty set

let names = Set<String>()
let names2: Set<String> = []

Declaring a set with default values

There are several ways to define a set with some initial values.

  • You can define the element type.
  • You can define the set and it will infer the type from the values to put in.
  • You can use one of the constructors available.
var genres: Set<String> = ["Rock", "Jazz", "Hip Hop"]
var genres2: Set = ["Rock", "Jazz", "Hip Hop"]
var genres3 = Set<String>(["Rock", "Jazz", "Hip Hop"])


["Jazz", "Rock", "Hip Hop"]
["Hip Hop", "Rock", "Jazz"]
["Rock", "Hip Hop", "Jazz"]

Adding a new element to a set



["Blues", "Rock", "Hip Hop", "Jazz"]

Adding a duplicate element

When we add a duplicate element in a set, it just ignores it



["Blues", "Rock", "Hip Hop", "Jazz"]

Iterating over a set

We can iterate over a set just like we iterate over an array.

for genre in genres {


Hip Hop

But you must be thinking we can do almost of this with arrays as well with some precautions then why do we need Sets.

Sets actually are not just simple arrays with no duplicate values, we can perform much more complicated operations on Sets. Basically the whole Mathematical Set Theory applies to Sets in Swift as well and is provides all the necessary methods to perform those operations. Lets take a look at some simple examples of those operations below.

1. Intersection: .intersection(_:)

When an intersection is performed between 2 sets, the result is a set of common elements between both sets.

let numbers1: Set = [1,3,5,7,8]
let numbers2: Set = [2,3,5,8,9,10]


[3, 8, 5]

2. Union: .union(_:)

The result of unions operation is the combination of all the elements from both sets

let numbers1: Set = [1,3,5,7,8]
let numbers2: Set = [2,3,5,8,9,10]


[1, 5, 7, 3, 2, 9, 10, 8]

3. Subtracting: .subtracting(_:)

The result is the removal of elements from the first set that present in the second set as well. Basically it is the opposite on union.

let numbers1: Set = [1,3,5,7,8]
let numbers2: Set = [2,3,5,8,9,10]


[1, 7]

4. Symmetric Difference: .symmetricDifference(_:)

It is the opposite on intersections. It removes the common elements and results in a set of non common elements from both sets.

let numbers1: Set = [1,3,5,7,8]
let numbers2: Set = [2,3,5,8,9,10]


[2, 1, 9, 10, 7]

Similar to above operations you can check for subsets, supersets, equal set etc,