Sling Academy
Home/Swift/Swift: Removing Elements from a Set (4 Examples)

Swift: Removing Elements from a Set (4 Examples)

Last updated: May 10, 2023

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.

Next Article: Subtracting 2 Sets in Swift (with Examples)

Previous Article: Iterating over a Set in Swift

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array