O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sum and product of an array

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required