I have question about returning NavigationView
and List
inside of SwiftUI body
There are code snippets like this:
var body: some View {
let trailingItem = HStack {
Button(action: { print("Button 1") }) {
Image(systemName: "bell")
}
Button(action: { print("Button 2") }) {
Image(systemName: "square.and.arrow.up")
}
}
return NavigationView {
Image("SwiftUI")
.navigationBarItems(trailing: trailingItem)
.navigationBarTitle("Title")
}
}
and this
var body: some View {
let numbers = [1, 2, 3, 4, 5]
return List(numbers, id: \.self) {
Text("\(String(describing: $0))")
}
}
In these two code snippets, I can find return
keyword for NavigationView
and List
To figure out what does that grammar do, I tried deleting return
keyword but nothing happened
I want to know:
What does that return
keyword do?
What is difference between using return
for NavigationView
and List
Thanks in advance for any help you are able to provide.
CodePudding user response:
Some of the features in SwiftUI's syntax are made possible by something called a View Builder which is a type of Result Builder
When using a View Builder, functions and computed properties have an implicit return (ie the last statement is returned even without the return
keyword). There are also other specific rules about what kinds of implicit code can be included in a View Builder, but let
declarations like your examples contain are fine. See https://swiftwithmajid.com/2019/12/18/the-power-of-viewbuilder-in-swiftui/ and https://swiftontap.com/viewbuilder for more information.
SwiftUI View
s are an interesting special case because the var body
property of the View
is interpreted to be a ViewBuilder
even though we don't have to explicitly annotate it with @ViewBuilder
. However, if you were to try the same thing in a regular function, you would need to use that @ViewBuilder
to get a similar result if the function had more than one statement (one-line functions in Swift have implicit returns as well).
@ViewBuilder func myView() -> some View {
Text("test")
Text("Another item")
}
So, in your code examples (since you were in var body
), there is no difference between using return
and omitting it.