But I dont understand why they refer to var: Self.Body
instead of just var: Body
If you have a type somewhere else in your code called Body
, how is the compiler to know which Body
you are referring to?
By using Self.Body
, the compiler knows you are referring to the associatedType Body
of the type that conforms to the View
protocol.
Is Body placeholder replaced with the actual View type (for example Text, Button, Image, VStack, etc?)
Yes, and those types can get very complicated very fast.
This View
:
struct ContentView: View {
@State var counter = 0
var body: some View {
VStack {
Button(action: { counter += 1 }, label: {
Text("Tap me!")
.padding()
.background(Color(.tertiarySystemFill))
.cornerRadius(5)
})
if counter > 0 {
Text("You've tapped \(counter) times")
} else {
Text("You've not yet tapped")
}
}
}
}
has a body
whose type is this:
VStack<TupleView<(Button<ModifiedContent<ModifiedContent<ModifiedContent<Text,_PaddingLayout>,_BackgroundModifier<Color>>,_ClipEffect<RoundedRectangle>>>,_ConditionalContent<Text, Text>)>>
* example from Thinking in SwiftUI v2.0 by Chris Eidhof and Florian Kugler