๐ŸŽ“ A1Learner
๐Ÿ”

Swift Map and Filter

Map and filter are two array methods that build new arrays from an existing array. Each method takes a closure that decides the work for every element.

Map changes every element

The closure doubles each number in the list. The prints show the list before the call, the new list, and the first list again.

let numbers = [1, 2, 3]
print(numbers)
let doubled = numbers.map { $0 * 2 }
print(doubled)
print(numbers)

Map can change the type

The closure gives back a count for each word. The new list holds numbers in place of text.

let words = ["cat", "horse", "ox"]
let lengths = words.map { $0.count }
print(lengths)

Filter keeps the evens

The closure checks the remainder after division by two. Only the numbers with a remainder of zero stay in the new list.

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

Reduce totals a list

The call starts from zero as its initial value. The closure adds each element into the running total in turn.

let numbers = [10, 20, 30]
let total = numbers.reduce(0) { $0 + $1 }
print(total)

Filter first, then map

The first step keeps the even numbers and prints them. The second step doubles that shorter list.

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

Example

let scores = [45, 80, 65, 90]
let passing = scores.filter { $0 >= 60 }
print(passing)
let curved = passing.map { $0 + 5 }
print(curved)

Key points

  • Map runs its closure on every element and collects each result.
  • The original array stays unchanged after a map call.
  • Filter keeps only the elements whose closure result is true.
  • Reduce combines all elements into one value.
  • A reduce call starts from an initial value.
  • Map and filter can chain in steps, one array at a time.

In this example, the filter closure keeps each score of 60 or more and prints 80, 65, and 90. The map closure then adds five to each kept score. The second print shows the raised scores as 85, 70, and 95.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does filter do with an element whose closure result is false?