Swift Array filter() with examples

In this Swift programming tutorial, you will learn about the Array filter() method with some easy-to-understand examples.

Before we go forward, let me explain what is the role of the filter method.

The Swift array filter() method returns elements from an array that satisfy the specific condition provided as the parameter.

You will provide a condition for the array using the filter() method and it will create a new array with only the elements of the existing array that satisfy the condition you provided.

Now see the example below:

// Using the Swift Array filter() method
var numbers = [1, 2, 3, 4, 5, 6, 7]

let numsFiltered = numbers.filter { $0 <= 4 }


[1, 2, 3, 4]

In the above code, we have used the filter method to get the elements that are less than or equal to 4.

The parameter provided for the filter() method is a closure where we specify the condition. In our case for the above code, it is { $0 <= 4 } .

Syntax of the Swift filter() method

Below is given the syntax of the Swift filter method:


In the above syntax, the array is an array and condition is the specified condition to filter the array elements. Here condition is the parameter of the filter method. This parameter is actually a closure that accepts the condition and returns a boolean value.

Examples of the filter method

Example 1:

// Using the Swift Array filter() method
var numbers = [6, 9, 10, 7, 8, 5, 4]

let numsFiltered = numbers.filter { $0 <= 7 }


[6, 5, 4]

In the above example, we have an array that contains integer values as its elements. We are using the filter() method to get the elements that are less than the value 7.

Example 2: Filter even numbers

Below is another example of using the filter method to return even numbers from the array:

var myNumbers = [13, 12, 6, 11, 3, 8, 15]

// Get the even numbers
var evenNumbers = myNumbers.filter({ $0 % 2 == 0 })



[12, 6, 8]

As you can see, we have successfully returned all the even numbers from our array.

Example 3: Return if array elements start with specific substring

Till now, we have seen examples of using the filter method to filter the array of integer-type elements. Well, we can also apply this method to an array that contains elements of string type.

See the example below:

var personNames = ["John", "Yusuf", "Joseph", "Sophia"]

// Returning the elements that start with "Jo"
var filteredNames = personNames.filter( { $0.hasPrefix("Jo") } )



[“John”, “Joseph”]

In the above example, we are returning the elements of the array that starts with “Jo”.

Here we are using the hasPrefix() method inside the filter() method. The hasPrefix() method can check if a string starts with a specific substring or not.