Higher Order Function in Swift

Level 4306 keystrokes

apply takes a function as a parameter and applies it repeatedly to a value. Doubling 2 three times gives 16, and adding 1 to 0 five times gives 5.

Swift code

// operation has the function type (Int) -> Int
1func apply(_ n: Int, times: Int, operation: (Int) -> Int) -> Int {
2 var result = n
// Repeats times times, feeding each result back in
3 for _ in 0..<times {
4 result = operation(result)
5 }
6 return result
7}
8
// Trailing closure as operation: 2 → 4 → 8 → 16
9let doubled = apply(2, times: 3) { $0 * 2 }
// 0 + 1 five times = 5
10let incremented = apply(0, times: 5) { $0 + 1 }
// Prints Doubled: 16 and Incremented: 5
11print("Doubled: \(doubled)")
12print("Incremented: \(incremented)")

Output

Doubled: 16
Incremented: 5
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.

  • (× 9
  • )× 9
  • :× 7
  • ,× 4
  • "× 4
  • {× 4
  • }× 4
  • =× 4
  • _× 2
  • -× 2

More Swift examples at level 4

← Swift typing practice