NavigationLink syntax

I’m trying to learn SwiftUI and Swift in general so I’m a total newbie here. I started by reading docs on Swift Language, making a console app and playing around with a bunch of concepts of the language there. Then I tried SwiftUI and immediately I see a bunch of syntax that wasn’t documented in the language itself.

So I dug around some more and I see there is a bunch of compiler and language magic going on behind the scenes which makes the syntax I see in SwiftUI work. A lot of the magic maybe isn’t so well documented. So I dug around and found answers to most of my questions about the SwiftUI syntax I’m seeing. Except this:

        NavigationView{
            VStack {
                Text("Select your device")
                
                List{
                    NavigationLink{
                       SensorView()
                    } label:{
                        Text("Raspberry Pi Zero")
                   }
                }
            }

What is with the label: statement outside of the curly braces for the NavigationLink closure all about? I can see in my app that it creates a label in the NavigationLink but I don’t understand why the label: is outside of the curly braces where it looks to me to be more or less detached from the NavigationLink it is seemingly associated with? I’m trying to understand this so I will know when/where to apply this pattern. I copied the code above from someone else’s sample.

Any insighgts or teachings would be appreciated.

>Solution :

This new syntax is part of Multiple Trailing Closures, which was released recently. Let’s look at your NavigationLink initializer:

init(destination: () -> Destination, label: () -> Label)

Here, there’s 2 parameters that take in closures: destination and label. So, that means you can write it like this (the plain, normal way):

NavigationLink(destination: {
    Text("The destination")
}, label: {
    Text("Click me!")
})

Or this, via trailing closure syntax:

NavigationLink(destination: {
    Text("The destination")
}) {
    Text("Click me!")
}

Or what you did in your question. Note: when you have multiple trailing closures, you need to add the argument label (for example label:) for all closures after the first.

NavigationLink {
    Text("The destination")
} label: {
    Text("Click me!")
}

Leave a Reply