A portrait painting style image of a pirate holding an iPhone.

by The Captain

May 14, 2023

Working with Sets in Swift

In Swift, a set is an unordered list of unique elements of a specified type. Each element in a set must be unique, as duplicated values are not allowed. This means that if you try to add a value that is already in the set, it will be ignored. Sets are useful when you need to work with a collection of elements where the order doesn't matter, but every element must be unique. The Set type in Swift is implemented as a hash table, which means that lookups are very fast, and the order of elements is not preserved.

Creating a Set

To create a set in Swift, you can use the Set type and pass in an array of elements. For example:
var mySet: Set = [1, 2, 3, 4, 5]}
Here, we have created a set of integers with values 1 to 5. Note that you need to specify the type of the set, and that the type must conform to the Hashable protocol. Alternatively, you can use the shorthand notation:
var mySet: Set = ["apple", "banana", "orange"]}
Here, we have created a set of strings. In this case, the type of the set is inferred from the contents of the array.

Working with Sets

Once you have created a set, you can perform a variety of operations on it.

Adding and Removing Elements

To add a new element to a set, you can use the insert() method:
To remove an element, you can use the remove() method:

Checking for Membership

To check if an element is in a set, you can use the contains() method:
if mySet.contains("apple") {
    print("The set contains an apple")

Set Operations

You can perform various set operations on sets, such as union, intersection, and difference. For example:
let set1: Set = [1, 2, 3]
let set2: Set = [3, 4, 5]

let unionSet = set1.union(set2) // {1, 2, 3, 4, 5}
let intersectionSet = set1.intersection(set2) // {3}
let differenceSet = set1.subtracting(set2) // {1, 2}
In this example, we have created two sets and then performed some set operations on them. The union() method returns a new set that contains all the elements from both sets, the intersection() method returns a new set that contains only the elements that are common to both sets, and the subtracting() method returns a new set that contains only the elements that are in the first set but not in the second set.


Sets are a versatile tool in Swift that can help you work with collections of unique elements. With the fast lookup times and convenient set operations, they are an excellent choice when you need to work with unordered but unique elements.