This concise, practical article will walk you through several unique examples that demonstrate how to remove single or multiple elements from a set in Swift. Without any further ado (like explaining what Swift is or talking about the history of the language), let’s get started.
Using the remove() method
In cases where you want to remove a specific element from a set based on its value, the remove()
method is the best choice. This method takes the element you want to remove as a parameter and returns it if it was a member of the set; otherwise, it returns nil
.
Example:
var mySet:Set<String> = ["Sling Academy", "Swift", "iOS"]
// remove "iOS" from the set
let removedElement: String? = mySet.remove("iOS")
// print the set after removing "iOS"
print(mySet)
Output:
["Sling Academy", "Swift"]
Removing a random element from a set
If you want to remove a random element from a set, just simply use the removeFirst()
method. Don’t let the name of the method confuse you (“removeFirst” doesn’t really mean “remove the first element”). A set in Swift is an unordered collection, so who can tell which is its first element?
Example:
var numbers = Set([1, 2, 3, 4, 5, 6, 7])
let firstNumber = numbers.removeFirst()
print("The removed number is \(firstNumber).")
print("The remaining numbers are \(numbers).")
Output:
The removed number is 4.
The remaining numbers are [3, 6, 7, 2, 1, 5].
Note that the output isn’t consistent due to the randomness.
Removing all elements from a set
The removeAll()
method can clear a set and leaves it empty.
var strings:Set<String> = ["a", "b", "c"]
strings.removeAll()
print("The set after removing all items: \(strings)")
Output:
The set after removing all items: []
Removing elements from a set based on a condition
In order to remove elements that satisfy a condition from a set, you can use the filter()
method.
Example:
var numbers: Set<Int> = [2, 3, 5, 7, 9, 11, 6, 10]
// get a new set with only even numbers
let evenNumbers: Set<Int> = numbers.filter { $0 % 2 == 0 }
// print
print(evenNumbers)
Output:
[10, 6, 2]
An alternative solution is to convert the set to an array, then call the removeAll(where:)
method on that array:
var numbers: Set<Int> = [2, 3, 5, 7, 9, 11, 6, 10]
var array = Array(numbers)
// remove all odd numbers from array
array.removeAll(where: { $0 % 2 != 0 })
// convert the array back to a set
numbers = Set(array)
// print the final result
print(numbers)
Output:
[2, 10, 6]
That’s it. Happy coding & have a nice day. If you have any questions about the examples in this article, please comment.