Think of it this way: instructions
is a function defined internally to the makeCake
function, only it has no body to it, just a declaration. The trailing closure supplies that missing function body. And how would you call a function named instructions
? Like so: instructions()
.
So let's say you've got something like this:
func instructions() {
print("Mix egg and flour")
}
func makeCake() {
print("Wash hands")
print("Collect ingredients")
instructions() //call the instructions function defined above
print("Here's your cake!")
}
But instead of hardcoding the instructions
function, you can turn it into a parameter to the makeCake
function:
func makeCake(instructions: () -> Void) {
print("Wash hands")
print("Collect ingredients")
instructions()
//since instructions is now a closure, you can call it by adding () after the name
print("Here's your cake!")
}
which you can then call like this:
makeCake(instructions: instructions)
//passing the name of the function makeCake will call internally
Or you can get rid of the explicit instructions
function and supply a closure instead;
makeCake(instructions: {
print("Mix egg and flour")
})
Which, using trailing closure syntax, can be shortened to:
makeCake {
print("Mix egg and flour")
}
In order for the closure makeCake to work, instructions must be called?
Yes, because otherwise the closure you are passing in as a parameter will not be given the chance to do its thing.