On the Apple SwiftUI Tutorial: Drawing Paths and Shapes , the following syntax is shown:
struct Badge: View {
var body: some View {
GeometryReader { geometry in
Path { path in
...
}
.fill(Color.black)
}
}
}
I did not see the syntax in the Swift docs on structs and feel very confused.
Additionally, how might one know that geometry
is "in" the GeometryReader
statement, whatever that means?
That has nothing to do with structs. That is closure syntax, where the variable name before in
is the input argument to the closure.
In the context of SwiftUI, that closure is actually a ViewBuilder
, which is a specific type of a function builder. You can read more about function readers and the other syntactic sugars that made SwiftUI possible here .
You can learn the type of the closure input argument(s) by option clicking on them in Xcode, just like any other variables. Or you can check the documentation of GeometryReader
to learn what input arguments its closure accepts.
This is simplified syntax of trailing closure, so
Path { path in
...
}
is just the same as
Path( { (path) in
...
})
of used Path
constructor
/// Initializes to an empty path then calls `callback` to add
/// the initial elements.
public init(_ callback: (inout Path) -> ())
By the way, this syntax is widely used in SwiftUI, so you will see the same in VStack {.. }
, GeometryReader { g in... }
, ScrollView {... }
and almost all others UI elements of SwfitUI framework.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.