I've been following Apple's SwiftUI tutorials, and the syntax seems really nice to use. In fact, the only problem I have with it is that I don't really understand how it works!
We can start off with the simplest possible View
:
struct ExampleView: View {
var body: some View {
Text("Hello world")
}
}
I understand what's going on here: body
is a read-only computed property, and the single Text()
expression is used as the return value of the getter. We can write this out "long-hand", and it still works:
struct ExampleView: some View {
var body: some View {
get {
return Text("Hello world")
}
}
}
Going back to the first version, instead of just returning a plain Text
view, we can wrap it in a VStack
:
struct ExampleView: some View {
var body: some View {
VStack {
Text("Hello world")
}
}
}
Now we are passing a lambda/closure to the VStack
constructor, which again implicitly returns a Text
object. So far, so good. But what I don't understand is what's going on here:
// ???
struct ExampleView: some View {
var body: some View {
VStack {
Text("Hello") // (1)
Text("World")
}
}
}
This looks for all the world as if the code on line (1) is calling the Text
constructor, building the object and then immediately throwing it away. The Text
object doesn't (appear to) register itself with the parent VStack
or anything like that in order to be displayed -- and yet some magic is clearly occurring, because the above results in two lines of text in output.
Can anybody enlighten me as to what exactly is happening here?