Instance MethodSwift

filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

Parameters

isincluded

A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.

Returns

An array of the elements that isIncluded allowed.

Overview

In this example, filter(_:) is used to include only names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"