Let's explore some practical examples of higher-order functions.
We can use our reduce
function to calculate the sum of a list of numbers as follows:
let listOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let sumOfNumbers = reduce(elements: listOfNumbers, initial: 0, combine: +) print(sumOfNumbers)
The result will be 55
, as expected.
We can use our reduce
function to calculate the product of array values as follows:
let productOfNumbers = reduce(elements: listOfNumbers, initial: 1, combine: *) print(productOfNumbers)
The result is going to be 3628800
, as expected.
We can use flatMap
to get values out of optionalArray
and remove nil
values:
let optionalArray: [String?] = ["First", "Second", nil, "Fourth"] let nonOptionalArray = optionalArray.flatMap { $0 } print(nonOptionalArray)
The result will be ["First", "Second", "Fourth"]
, as expected.