Instance Method

filter(_:)

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

Declaration

func filter(_ isIncluded: (Int) throws -> Bool) rethrows -> [Int]

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.

Return Value

An array of the elements that isIncluded allowed.

Discussion

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"]"

Complexity: O(n), where n is the length of the sequence.

See Also

Selecting Elements

func filteredIndexSet(in: Range<IndexSet.Element>, includeInteger: (IndexSet.Element) -> Bool) -> IndexSet

Returns an IndexSet filtered according to the result of includeInteger.

func filteredIndexSet(includeInteger: (IndexSet.Element) -> Bool) -> IndexSet

Returns an IndexSet filtered according to the result of includeInteger.

func prefix(Int) -> Slice<IndexSet>

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

func prefix(through: IndexSet.Index) -> Slice<IndexSet>

Returns a subsequence from the start of the collection through the specified position.

func prefix(upTo: IndexSet.Index) -> Slice<IndexSet>

Returns a subsequence from the start of the collection up to, but not including, the specified position.

func prefix(while: (Int) -> Bool) -> Slice<IndexSet>

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

func suffix(Int) -> Slice<IndexSet>

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

func suffix(from: IndexSet.Index) -> Slice<IndexSet>

Returns a subsequence from the specified position to the end of the collection.