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) -> Int1func apply(_ n: Int, times: Int, operation: (Int) -> Int) -> Int {2 var result = n // Repeats times times, feeding each result back in3 for _ in 0..<times {4 result = operation(result)5 }6 return result7}8 // Trailing closure as operation: 2 → 4 → 8 → 169let doubled = apply(2, times: 3) { $0 * 2 }// 0 + 1 five times = 510let incremented = apply(0, times: 5) { $0 + 1 }// Prints Doubled: 16 and Incremented: 511print("Doubled: \(doubled)")12print("Incremented: \(incremented)")Output
Doubled: 16 Incremented: 5
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