0Pricing
Swift Academy · Lesson

filter and Predicates

Select elements that satisfy a condition.

What Is filter?

filter keeps only the elements for which a closure (a predicate) returns true.

  • The closure returns a Bool
  • The element type stays the same
  • The result is a new array, possibly smaller

A Simple filter

Keep only the even numbers:

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

All lessons in this course

  1. map and compactMap
  2. filter and Predicates
  3. reduce and reduce(into:)
  4. flatMap and Chaining
← Back to Swift Academy