Swift set remove()

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

Example

// 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:

set.remove(element)

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!)

Output

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?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges