Swift Set - Removing Elements

In this article, we will explain how to remove elements from a Swift Set.

Removing Elements from a Set with remove()

In Swift, you can use the remove() method to remove a specific element from a Set.

The remove() method returns the removed element, so if you need the removed value, you can assign it to a variable.


Let's try removing an element from a Set using the remove() method.

Since the Element returned by remove() is optional, we specify a default value of "Not found" in case the element does not exist and nil is returned.

var numbers: Set = [1, 2, 3, 4, 5]
print(numbers)

let removed = numbers.remove(4)
print(numbers)
print(removed ?? "Not found")

The output will be as follows. The specified value 4 is removed from the numbers Set and retrieved in removed.

[2, 5, 3, 4, 1]
[2, 5, 3, 1]
4

Removing the First Element of a Set with removeFirst() / popFirst()

If you want to remove the first element of a Swift Set, use the removeFirst() or popFirst() methods.

Both methods remove the first element of the Set and return it as the result.

The difference is that popFirst() works even if the Set is empty, while removeFirst() will cause an error if the Set has no elements.

The element returned by popFirst() is optional, and if the Set is empty, it returns nil.


Now, let's use removeFirst() and popFirst() to remove elements.

var numbers: Set = [1, 2, 3, 4, 5]
print(numbers)

let removed1 = numbers.removeFirst()
print(numbers)
print(removed1)

let removed2 = numbers.popFirst()
print(numbers)
print(removed2 ?? "Not found")

The output will be as follows. The first elements of numbers are removed and retrieved in removed1 and removed2 respectively.

[3, 4, 2, 1, 5]
[4, 5, 2, 1]
3
[5, 2, 1]
4

Swift Set – Removing Elements 1


Removing All Elements of a Set with removeAll()

If you want to remove all elements of a Swift Set, use the removeAll() method.

Let's remove all elements using removeAll().

var numbers: Set = [1, 2, 3, 4, 5]
print(numbers)

numbers.removeAll()
print(numbers)

The output will be as follows. You can see that all elements are removed.

[5, 3, 1, 2, 4]
[]

That wraps up how to remove elements from a Swift Set.