@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content
I am self-learning swift. Please help.
- what can I call the name of the above code style? Callback, function,..?
- I want to set optional for some cases, how to do that?
CodePudding user response:
- It's kind of callback, called
closure
, more information here: https://docs.swift.org/swift-book/LanguageGuide/Closures.html - If you want to set optional just adding suffix like
SwiperElement?
CodePudding user response:
@ViewBuilder is a custom parameter attribute that constructs views from closures. https://developer.apple.com/documentation/swiftui/viewbuilder
Use buildif for optional content when using view builder https://developer.apple.com/documentation/swiftui/viewbuilder/buildif(_:)
CodePudding user response:
First of all
@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content
Is not a valid syntax: you need to either specify a var
, in which case you don't need to say @escaping
:
@ViewBuilder var content: (SwiperElement, SwiperItemResource, Dragging) -> Content
or define a func
, where you can say the closure is @escaping
:
@ViewBuilder func myFunc(content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content) -> some View { ... }
In first case you declare a variable, which stores a type called Closure. This type has 3 inputs SwiperElement, SwiperItemResource, Dragging
, and 1 output of type Content
.
In second case you define a function, which will get a closure as its argument. Keywords @escaping
means that the closure will outlive the function itself (i.e. when function returns, it's possible that closure is still running).
Regarding optionals, depends what you mean. If you want to set some parameters as optional, you just add ?
to them:
var x(SwiperElement?, SwiperItemResource?, Dragging?) -> Content?
but if you are talking about optional UI elements, then you may need to get familiar with SwiftUI @State
, e.g. as explained here