Hello,
Look at this SwiftUI view:
struct ContentView: View { var body: some View { Text("Hello !") } }
The Text("Hello") line is a closure. Am I wrong ?
There is an implicit return. I can write this:
struct ContentView: View { var body: some View { return Text("Hello !") } }
I can put multiple lines like this:
struct ContentView: View { var body: some View { Text("Hello !") Text("Hello2 !") } }
I don't understand how works internally the implicit return in this case because we have 2 components.
Also, can you explain me why i can't put a basic swift line code like this:
struct ContentView: View { var body: some View { Text("Hello !") print("Hello") Text("Hello2 !") } }
Thanks
var body is a view builder, so, body expect a View to be returned.
Doc explains: https://developer.apple.com/documentation/swiftui/viewbuilder
You typically use ViewBuilder as a parameter attribute for child view-producing closure parameters, allowing those closures to provide multiple child views. For example, the following contextMenu function accepts a closure that produces one or more views via the view builder. Clients of this function can use multiple-statement closures to provide several child views. When you have a single subview, you can add return or omit.
When you have multiple subviews, SwiftUI automatically builds a view, grouping all of them.
This is equivalent to :
struct ContentView: View { var body: some View { return Group { Text("Hello !") Text("Hello2 !") } } }
So, you cannot have a print statement in it, because that's not a view.