Swift Array – Remove Elements based on Condition

To remove elements from an Array in Swift, based on a condition or predicate, call removeAll(where:) method on the array and pass the condition/predicate to where parameter.

The syntax to call removeAll() method on the array is

</>
Copy
arrayName.removeAll(where: condition)

where parameter accepts a predicate which returns boolean value. The elements that satisfy the condition, meaning which return true for the condition shall be removed from the array.

Example

In the following program, we will take an array fruits with five string elements, and remove those elements which contain the letter n.

main.swift

</>
Copy
var fruits = ["apple", "banana", "cherry", "mango", "guava"]
fruits.removeAll(where: {$0.contains("n")})
print(fruits)

Output

Swift Array - Remove Elements based on Condition

Elements that contain "n" have been removed from the array.

Conclusion

In this Swift Tutorial, we learned how to remove elements from an Swift Array based on given condition.