Swift Array filter()

In this tutorial, we will learn about the Swift Array filter() method with the help of examples.

The filter() method returns all the elements from the array that satisfy the provided condition.

Example

var numbers = [2, 3, 6, 9]

// return all the elements greater than 5 var result = numbers.filter({ $0 > 5})
print(result) // Output: [6, 9]

filter() Syntax

The syntax of the filter() method is:

array.filter(condition)

Here, array is an object of the Array class.


filter() Parameters

The filter() method takes one parameter:

  1. condition - a closure that accepts a condition and returns a Bool value.

filter() Return Value

  • returns all the elements from the array that satisfy the provided condition

Example 1: Swift Array filter()

var languages = ["Swedish", "Nepali", "Slovene", "Norwegian"]

// return all the elements that start with "N" var result = languages.filter( { $0.hasPrefix("N") } )
print(result)

Output

["Nepal", "Norwegian"]

In the above program, notice the closure definition,

{ $0.hasPrefix("N") }

This is a short-hand closure that checks whether all the elements in the array have the prefix "N" or not.

$0 is the shortcut to mean the first parameter passed into the closure.

The closure returns a Bool value depending upon the condition. If the condition is

  • true - the array value is kept
  • false - the array value is dropped/omitted

And finally, all the elements that start with "N" are stored in the result variable.


Example 2: Return Only Even Numbers From Array

var numbers = [2, 4, 5, 7, 8, 9]

// check if all elements are even numbers or not var result = numbers.filter({ $0 % 2 == 0 })
print(result)

Output

[2, 4, 8]
Did you find this article helpful?