UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Confused about how this trailing closure works (Day 9 Trailing Closure Review)

Forums > 100 Days of SwiftUI

I know that makeCake can infer the parameter and return, but I'm still kinda confused on how this is working. I commented out instructions() and noticed "Mix egg and flour" doesn't display. In order for the closure makeCake to work, instructions must be called?

func makeCake(instructions: () -> Void) {
    print("Wash hands")
    print("Collect ingredients")
    instructions()
    print("Here's your cake!")
}
makeCake {
    print("Mix egg and flour")
}

2      

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.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.