Learn

A higher order function is a function that takes a closure as input or a functions that returns a closure. This is something we have defined ourselves already in the previous exercises. In this exercise we’re going to take a look at some higher-order functions provided by Swift to help with common programming operations. The most common are filter, sort, map and reduce. Each of these are functions that take a closure as input and perform operations with the given closure.

We’re going to take a look at the filter function. We have an array of test grades below and we want to filter out the failing grades.

var grades = [85, 76, 59, 47, 91, 88, 99, 64, 77, 50, 60, 80]

We want to filter out the grades that are below 60. Swift’s built-in filter function allows us to do just this. We provide a closure to the function telling it what we want to be filtered, and the function returns an array of integers that meet the criteria. Let’s take a look at this in action:

let passingGrades = grades.filter { (grade) -> Bool in return grade >= 60 }

Pretty cool. Swift provides a filter function on collections which we can use to easily filter our data. Above, we call filter on grades with the dot syntax, and provide an inline closure to define exactly what we want to include in the array. This is saying, “Include any grade that is greater than or equal to 60”.

If you recall from the syntactic sugar exercise, we can shorten the calling code:

let passingGrades = grades.filter { $0 >= 60 }

Similarly, there is a sorted(by:) function for collections which we can use to sort data. Let’s sort our grades array from lowest the lowest score to the highest:

print(grades.sorted(by: <)) // prints [47, 50, 59, 60, 64, 76, 77, 80, 85, 88, 91, 99]

How convenient!

Instructions

1.

Using the filter function from above, filter the names array to only include those that begin with “A” and assign it to a constant named aNames. Use shorthand arguments and exclude the return keyword. Print the result to the console.

2.

Use Swift’s higher-order function sorted(by:) to sort the names array alphabetically and assign the result to a variable named sortedNames. Print the result to the console.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?