Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.