Swift set remove()

In this tutorial, we will learn about the Swift Set remove() method with the help of examples.

The remove() method removes the specified element from the set.


// create an set
var numbers: Set = [2, 3, 5, 7, 9, 11]

// remove 11 from the set numbers.remove(11)
// print updated numbers set print(numbers) // Output: [3, 5, 9, 7, 2]

remove() Syntax

The syntax of the set remove() method is:


Here, set is an object of the Set class.

remove() Parameters

The remove() method takes only one parameter:

  • element - the element to be removed from the set

remove() Return Value

  • returns the element that was removed from set.

Note: If the element is not a member of set, the method returns nil.

Example: Swift Set remove()

// languages set
var languages = ["Swift", "C", "Objective-C"]

print("Before Removing:", languages)

// "Objective-C" (at index 2) is removed var removed = languages.remove(at: 2)
print("After Removing:", languages) print("Removed Element:", removed!)


Before Removing: ["Objective-C", "Swift", "C"]
After Removing: ["Swift", "C"]
Removed Element: "Objective-C"

Here, we have removed "Objective-C" from the languages set. The removed element is stored in the removed variable.

We have used ! to force unwrap the optional returned by remove()

print("Removed Element:", removed!)

To learn more about forced unwrapping, visit Optional Forced Unwrapping.

Did you find this article helpful?