WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Question: Closure syntax

Forums > 100 Days of SwiftUI

Hi I'm re-reading Pauls' tutorial on Closures. https://www.hackingwithswift.com/quick-start/beginners/how-to-accept-functions-as-parameters

I noticed that when calling the function, there is : after second and third, but there's no : after the first.


func doImportantWork(first: () -> Void, second: () -> Void, third: () -> Void) {
    print("About to start first work")
    first()
    print("About to start second work")
    second()
    print("About to start third work")
    third()
    print("Done!")
}

// call the function
doImportantWork {
    print("This is the first work")
} second: {
    print("This is the second work")
} third: {
    print("This is the third work")
}

I saw this happens also in projects's tutorial's codes.

My question is : When to use : and when to attach the {} directly ?

Thanks in advance

2      

Only the first one uses just the opening and closing brace, all subsequent ones with use the paramater label followed by a colon.

Taken from the Unwrap App, Trailing closure syntax

func travel(action: () -> Void) {
    print("I'm getting ready to go.")
    action()
    print("I arrived")
}

travel {
    print("I'm driving in my car")
}

When the last parameter is a closure we can call travel() using trailing closure syntax. In other words we use {}. Then the following closures will be formated differentely, with the end brace from the previous closure, the external parameter name and a colon, and then another brace.

https://www.hackingwithswift.com/quick-start/beginners/how-to-accept-functions-as-parameters

When it comes to calling that, the first trailing closure is identical to what we’ve used already, but the second and third are formatted differently: you end the brace from the previous closure, then write the external parameter name and a colon, then start another brace.`

Example with a button:

struct ContentView: View {
    @State private var tapCount = 0

    var body: some View {
        VStack {
            Text(String(tapCount))
            Button {
                tapCount += 1
            } label: {
                Text("Tap me!")
            }
        }
    }
}

2      

Alert is another one that shows an example of this. There's probably tons more that I haven't learned yet as well.

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        VStack {
            Button {
                showingAlert = true
            } label: {
                Label("Show alert", systemImage: "alarm")
            }
        }
        .alert("Showing Alert", isPresented: $showingAlert) {
            Button("OK") {}
        } message: {
            Text("This is an alert.")
        }
    }
}

2      

Vince has the right answer. The syntax you see is the result of using multiple trailing closures. It's great that you see this and are asking questions. We see the gears working in your head to make sense of SwiftUI. Nice!

Usually I might derive some car, or house-based example to help clarify this concept. But at this point in your development, you might want to know that when Swift was first released, trailing closure syntax was available, but only if the LAST parameter in a function's signature was itself a function.

From the start, developers wanted more! Why not have multiple trailing closures?

One of the ways that Swift evolves is for the Swift community to propose changes. These changes include detailed proposals and examples on how new syntax might work, and of course includes a wonderful essay on the many benefits to humanity.

Other developers get to weigh in and give their thoughts as to why the proposal is complete rubbish, and would produce rabid code devils that would plague humans forever.

Some proposals die a long and painful death. Your new friend Multiple Trailing Closures survived the ordeal!

Take a look at this github repository for some of the juicy details and comments.

Proposal: Multiple Trailing Closures

2      

@twostraws gets very exicited when Apple adds new capabilities to Swift and SwiftUI.

So much so, he publishes entire videos explaining new features with references to the original Swift evolution proposals.

Here's a link to his video on new stuff in Swift 5.5.

See: What's New in Swift 5.5

Take a quick peek at the article. See the references to SE-0296 ? This is the original proposal for Async / Await syntax.

2      

I struggled with that too. Thanks for your question and also thanks for the answers.

2      

Thank you @vtabmow,@Obelix, @FirstTraveller.

@vtabmow the example of button is very helpful to demonstrate how to use it in the real world.

Have a nice day,

Boat

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.