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

The flatMap function in terms of reduce

To understand the power of reduce, we can implement the flatMap function in terms of reduce as well:

func flatMapIntermsOfReduce<Element>(elements: [Element], transform: (Element) -> Element?) -> [Element] {   return reduce(elements: elements, initial: []) {         guard let transformationResult = transform($1) else {             return $0         }         return $0 + [transformationResult]     } } let anArrayOfNumbers = [1, 3, 5] let oneDimensionalArray = flatMapIntermsOfReduce(elements: anArrayOfNumbers) { $0 + 5 } 

Also, we can flatten a two-dimensional array using the reduce method as follows:

func flatMapIntermsOfReduce<Element>(elements: [[Element]], transform: (Element) -> Element) -> [Element] {  return elements.reduce([]) ...

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