Filter and Reduce in Swift

Level 3130 keystrokes

filter keeps the even numbers of the array, and reduce adds up all of its elements. It prints [2, 4, 6] and 21.

Swift code

// An array of the integers 1 to 6
1let nums = [1, 2, 3, 4, 5, 6]
// Keeps only elements where $0 % 2 == 0 (the even ones)
2let evens = nums.filter { $0 % 2 == 0 }
// Starts at 0 and adds each element: $0 is the running total, $1 the element
3let sum = nums.reduce(0) { $0 + $1 }
// Prints [2, 4, 6]
4print(evens)
// Prints 21 (1 + 2 + … + 6)
5print(sum)

Output

[2, 4, 6]
21
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • ,× 5
  • =× 5
  • (× 3
  • )× 3
  • $× 3
  • .× 2
  • {× 2
  • }× 2
  • [× 1
  • ]× 1

More Swift examples at level 3

← Swift typing practice