I found this chapter a little tricky, simply because I’m a little newer to functional programming. Reducing the closures from long, expressive syntax to just a few characters and have it essentially do the same thing is both beautiful and frightening at the same time, so I made sure to go through this a few times just to make sure I understood it.
Anyway, on to my solutions:
Bronze Challenge 1:
This one I found a little too straightforward–instead of assigning the sort to another variable, you can just sort it.
Note: In the documentation,
sort()
is said to sort an array in-place, however, when using that function I get a compile error sayingsort()
is replaced withsorted()
. Not sure why, but the documentation seems to be a little behind the compiler.
volunteerCounts.sorted { $0 < $1 }
print(volunteerCounts)
Bronze Challenge 2:
Again, kinda straightforward. Instead of sorted(by:)
, you just leave off the parameter.
volunteerCounts.sorted()
print(volunteerCounts)
Gold Challenge
This one I wanted to follow through similar to how we reduced the sorted(by:)
function at the beginning of the chapter. To begin with, we have this:
let totalProjection = projectedPopulations.reduce(0, {
(accumulatedProjection: Int, precinctProjection: Int) -> Int in
return accumulatedProjection + precinctProjection
})
Side note: I don’t like
reduce(0){}
simply because, coming from other languages, this seems a little disjointed. If they are both in the method parameter body, it makes it a little more obvious what’s going on and what applies to what. Just a preference though.
Simplify that a bit by trimming the type information (which can be inferred):
let totalProjection = projectedPopulations.reduce(0, {
accumulatedProjection, precinctProjection in
accumulatedProjection + precinctProjection
})
But again, we can get that to be way more concise. My final solution:
let totalProjection = projectedPopulations.reduce(0, { $0 + $1 })
I encourage everyone to update this forum with their own solutions as they’re going along. Looking forward to providing solutions to other chapters!