Learn

So far we have defined closures without arguments or return values. Just like with functions, it’s very useful for our closures to be able to accept inputs, perform tasks with the inputs, and return a value. Let’s see how we can do that with closures.

Word of our closure aptitude is getting out… We have been tasked by the science division to create a closure that converts meters into feet for use in their super-secret project.

First off, we need the formula for converting meters into feet:

LengthInFeet = LengthInMeters * 3.281

Let’s see how we can represent this as a closure and then break it down. This time we will declare the types within the open brace, but they could also be defined after the variable name using type annotation as in the previous exercise.

let metersToFeet = { (meters: Double) -> Double in return meters * 3.281 }

We define a closure that takes a Double as an argument. We name the argument meters, and the closure returns a value of type Double. The closure execution, following the in keyword, uses the formula above to convert the input argument meters into feet. The closure is assigned to a constant named metersToFeet.

And here is what declaring the types after the variable name with type annotation looks like:

let metersToFeet: (Double) -> Double = { meters in return meters * 3.281 }

We can even use type inference define the closure:

let metersToFeet = { meters in return meters * 3.281 }

Swift knows that the type of metersToFeet must be (Double) -> Double because the only type that can be multiplied by 3.281 is a Double.

Let’s test it out by calling a few landmarks:

print(metersToFeet(1)) // prints “3.281” // the height of the eiffel tower: print(metersToFeet(324)) // prints “1063.044” // the height of the empire state building: print(metersToFeet(443.2)) // prints “1454.2”

Looks pretty good! The science division is going to be very happy with our work!

Instructions

1.

Use type annotation to define a closure that takes two integers and returns the sum. Assign it to a constant named add.

2.

Call the closure in the following line by adding two numbers and 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?