Swiftly

Swift 5.7 references for busy coders

filter

filter is a functional method that returns an array containing only the elements of a sequence that satisfy a given predicate, in their original order.

filter over array of Ints

let numbers = [1, 2, 3, 4, 5, 6, 7]
let numbersLessThan5 = numbers.filter { $0 < 5 }
print(numbersLessThan5) // [1, 2, 3, 4]

filter over array of Strings

import Foundation // Required for `String.contains()` method

let words = ["pineapple", "grapple", "banana", "applet"]
let wordsContainingApple = words.filter { $0.contains("apple") }
print(wordsContainingApple) // ["pineapple", "grapple", "applet"]