Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Closures in Swift 2 Building Standard Library Functions Reduce

Getting Map, Reduce, Filter, and Sort straight

I just want to make sure I'm accurately understanding the built-in higher order functions. Here's what I know:

-Map: applies a function to every item (e.g. multiply every item by 2)

  • Takes 1 argument: a closure
  • Closure takes 1 argument: an element

-Reduce: reduces collection to single value (e.g. sum)

  • Takes 2 arguments: initial value and a closure
  • Closure takes 2 arguments: the running subtotal and the next element.

-Filter: filters out the collection to keep only items that satisfy a condition (e.g. < 10)

  • Takes 1 argument: a closure
  • Closure takes 1 argument: an element

-Sort: sorts function (e.g. from least to greatest)

  • Takes 1 argument: a closure
  • Closure takes 2 arguments: first element and second element ($0, $1), which are compared against each other.

Please correct what I have above if anything is off, thanks! :)

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Christine Chang,

Yes your understanding of the Swift Standard Library's higher order functions is on point. You should check out some of the other higher order functions in the SSL. Such as, flatMap, sortInPlace, combine. I have found them both particularly useful in my work.

Here is some additional reading if it interests you :)

Swift Guide to Map, Filter, Reduce

Higher Order Functions: Map, Filter, Reduce

Higher Order Functions in Swift

Sorry for not going into much detail with my response. If you have any further questions I will gladly answer them for you.

EDIT: I would also like to make sure you understand that these functions return newly created arrays with the sorted, filtered, or mapped values. The original array is not modified. You will still have both the original collection and the resulting collection that was created by your specifications. However, the exception to this is sortInPlace that actually mutates the original array being sorted and does not return a new array.