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

SOLVED: Question: Closure syntax

Forums > 100 Days of SwiftUI

@boat  

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

3      

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!")
            }
        }
    }
}

3      

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.")
        }
    }
}

3      

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

3      

@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.

3      

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

3      

@boat  

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

1      

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.