Member-only story
Create Your Own Reduce Function in Swift
There’s an Iterator…and…
Reduce makes an Array a single function that is it combines all of the given elements in an array and outputs a single value (more on that in a minute) — according to the function we give it.
How is that implemented? What do we do?
Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites:
- Be able to code Swift using Playgrounds
Terminology
Array: An ordered series of objects which are the same type
Dictionary: The association between keys and values (where all the keys are of the same type, and all values are of the same type)
Reduce: A higher-order function that returns the result of combining the elements of a sequence using a closure
The Motivation
Reduce
is one of the coolest higher — order functions available to us in Swift.
What if we could look about how reduce
works under the hood, and perhaps mangle the functionality to be…whatever we would want it to be.
The reduce function
The original
The classic, canonical use is to use reduce to perhaps sum an Array
var arr = [1,2,3,4]
arr.reduce(0, {$0 + $1}) //10
This is, of course, using lots of magic from Swift’s type inference. The longer version (for the same array arr
) does have the same result
arr.reduce(0, { sum, newVal in
return sum + newVal
}) // 10
which makes it slightly easier to read for beginners, and slightly more tricky for the more experienced (you can’t win).
There are variations on uses for the reduce function. Although Reduce works on any array it doesn’t have to return an Integer (like the example above) but can return other types.
What about returning a String to concatenate an array?
var names = ["James", "Ahemed", "Kim"]
names.reduce("", {$0 + $1})
This version of reduce
just concatenates the array
of Strings.