Lesson 11 of 15
Higher-Order Functions
Higher-Order Functions
Swift arrays have powerful built-in higher-order functions:
map — transform each element
let nums = [1, 2, 3, 4]
let doubled = nums.map { $0 * 2 } // [2, 4, 6, 8]
filter — keep elements matching a predicate
let evens = nums.filter { $0 % 2 == 0 } // [2, 4]
reduce — combine all elements into one value
let total = nums.reduce(0) { $0 + $1 } // 10
Chaining
let result = nums.filter { $0 % 2 == 0 }.map { $0 * $0 } // [4, 16]
The shorthand $0, $1, etc. refer to the first and second closure arguments.
Your Task
Write a function sumOfSquaresOfEvens that takes an array of integers and returns the sum of the squares of all even numbers. Use filter, map, and reduce.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.