VStack initialization without parentheses

Hi everyone I'm new to swiftui and I'm trying to understand the reason that allows swiftui to call a VStack or any other container view without parentheses as in:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("sth");
        }
    }
}

After looking into the swift docs, it was clear as in any other programming language that instantiating a class/structure is made by calling the entity with its parentheses, an even passing some parameters if possible. Isn't should be the case for placing view components in the body computer property?

So far my mind keeps telling me that the syntax should follow this convention

struct ContentView: View {
    var body: some View {
        VStack() {
            Text("sth");
        }
    }
}

At which concept should I look into for further clarifications

All the best.

Accepted Reply

More details here, in Swift Programming language (functions & closures):

« A closure passed as the last argument to a function can appear immediately after the parentheses. When a closure is the only argument to a function, you can omit the parentheses entirely. »

The Swift Programming Language (Swift 5.7)

  • Thanks much @Claude31 that's the information I was looking for. It was helpful!

Add a Comment

Replies

The init is defined as:

init(
    alignment: HorizontalAlignment = .center,
    spacing: CGFloat? = nil,
    @ViewBuilder content: () -> Content
)

So, you can also call

struct ContentView: View {
    var body: some View {
        VStack(content:  {
            Text("sth")
        })
    }
}

The Stack { } where the content (closure) is outside the parameters list, is just a writing facility.

You can do the same in other Swift functions:

array.map() { closure }
or
array.map { closure}

More details here, in Swift Programming language (functions & closures):

« A closure passed as the last argument to a function can appear immediately after the parentheses. When a closure is the only argument to a function, you can omit the parentheses entirely. »

The Swift Programming Language (Swift 5.7)

  • Thanks much @Claude31 that's the information I was looking for. It was helpful!

Add a Comment