Swift String removeAll()

The removeAll() method removes all the elements from the string based on a given condition.

Example

var string = "Hello World"

// characters to be removed
var text: Set<Character> = ["H", "W"]

// remove "H" and "W" from string string.removeAll(where: { text.contains($0) })
print(string) // Output: ello orld

removeAll() Syntax

The syntax of removeAll() is:

string.removeAll(where: condition)

Here, string is an object of the String class.


removeAll() Parameters

The removeAll() method takes a single parameter:

  • condition - a closure which accepts a condition and returns a bool value. If the condition is true, the specified characters are removed from string.

removeAll() Return Value

The removeAll() method doesn't return any value. It only removes characters from the string.


Example: Swift removeAll()

var text = "Remove Repeated Words"

let remove: Set<Character> = ["e", "R", "o", "S"]

text.removeAll(where: { remove.contains($0) })
print(text) // Output: mv patd Wrds

In the above example, we have created a set named remove with characters that are to be removed from the string text.

We have defined the closure {remove.contains($0)} to remove the repeated characters.

$0 is the shortcut to mean that the first element of the remove set is passed into the closure.

Did you find this article helpful?