How to remove all elements of an array in Swift

Overview

We can remove all elements of an array that satisfy a given predicate in Swift by using the removeAll(where:) method.

Syntax

arr.removeAll(where:)

Parameters

where:: This is a criteria, condition, or predicate. Once this is met, the element is removed.

Return value

The value returned is an array with the elements that meet the criteria to be removed.

Code example

// create arrays
var languages = ["Java", "Python", "Ruby", "Perl", "Swift"]
var numbers = [1, 2, 3, 4]
// remove based on criteria
languages.removeAll {$0.count > 4}
// remove strings whose length
// is greater than 4
numbers.removeAll{$0 % 2 != 0}
// remove numbers that
// are not even numbers
// print modified arrays
print(languages)
print(numbers)

Explanation

  • Lines 2 and 3: We create the arrays languages and numbers.
  • Line 6: We remove string elements with a length greater than 4 from the array languages.
  • Line 10: We remove elements that are not even numbers from the array numbers.
  • Lines 15 and 16: We print the results to the console.