@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content
我自学很快。请帮忙。
- 以上代码样式的名称可以叫什么?回调,函数
- 我想为某些情况设置可选,如何做到这一点
- 这是一种回调,称为
closure
,更多信息请点击此处:https://docs.swift.org/swift-book/LanguageGuide/Closures.html - 如果您想设置可选,只需添加后缀,如
SwiperElement?
@ViewBuilder是一个自定义参数属性,用于从闭包构造视图。https://developer.apple.com/documentation/swiftui/viewbuilder
使用视图生成器时,对于可选内容,请使用buildifhttps://developer.apple.com/documentation/swiftui/viewbuilder/buildif(_:(
首先是
@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content
不是有效的语法:您需要指定var
,在这种情况下,您不需要说@escaping
:
@ViewBuilder var content: (SwiperElement, SwiperItemResource, Dragging) -> Content
或者定义一个func
,可以说闭包是@escaping
:
@ViewBuilder func myFunc(content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content) -> some View { ... }
在第一种情况下,您声明一个变量,该变量存储一个名为Closure的类型。该类型具有3个SwiperElement, SwiperItemResource, Dragging
输入端和1个Content
输出端。
在第二种情况下,您定义了一个函数,该函数将获得一个闭包作为其参数。关键字@escaping
意味着闭包将比函数本身更持久(即,当函数返回时,闭包可能仍在运行(。
关于期权,取决于你的意思。如果您想将一些参数设置为可选参数,只需在其中添加?
即可:
var x(SwiperElement?, SwiperItemResource?, Dragging?) -> Content?
但是,如果你谈论的是可选的UI元素,那么你可能需要熟悉SwiftUI@State
,例如这里解释的