Up until this point we have been fairly explicit about defining the type of the closure, assigning it to a variable, and passing the variable to a function. With Swift being a strongly typed language, we can use type inference to our advantage and cut down on our coding footprint. This means we can define closures as we call functions without having to assign it to a variable.
On top of that, Swift has a feature named “Trailing Closures.” If a closure is the last argument in a function, we can write the trailing closure after the function’s closing parenthesis, inline with the function. Let’s take a look at a common task that accepts a closure:
func networkRequest(endAction: () -> Void) { // Get data from online completion() }
Above we have a function named networkRequest
which accepts a closure as an argument named completion
. The closure has no inputs or outputs. Rather than defining a closure and assigning it to a variable, we can define the closure inline when we call the function:
networkRequest(endAction: { print(“Data loaded!”) })
Pretty neat huh? This is referred to as an inline closure and is used extensively in Swift. Also, because the closure is the last argument in the function declaration, we can omit the parameter name when calling it:
networkRequest { print(“Data loaded!”) }
In Swift, you can have multiple trailing closures:
func networkRequest(startAction: () -> Void, endAction: () -> Void) { startAction() // function execution endAction() }
Can be called:
networkRequest { print(“Starting to load!”) } endAction: { print(“Data loaded!”) // closure 2 statements }
We expand the networkRequest
to accept two closures as arguments. Because these are the last two arguments of the function declaration, we can provide inline, trailing closures as arguments.
Instructions
Create a function named bake
that takes a String
and a closure as arguments. The argument names should be ingredient
and completionAction,
respectively. The closure should accept a String
and return no values.
Within the bake function, print “Baking {ingredient}” to the console. Then, on the next line, call the closure passing in ingredient
as its argument.
Below this definition, call the bake
method with an ingredient as the name input, and an inline trailing closure that prints “Finished baking {ingredient}” to the console.