Swift set remove()

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

Example


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

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.