[英]Swift @escaping params optional
@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content
I am self-learning swift.我是自学swift。 Please help.
请帮忙。
closure
, more information here: https://docs.swift.org/swift-book/LanguageGuide/Closures.htmlclosure
,更多信息在这里: https://docs.swift.org/swift-book/LanguageGuide/Closures.ZFC35FDC70D5FC69AD269883A82EZ7SwiperElement?
SwiperElement?
@ViewBuilder is a custom parameter attribute that constructs views from closures . @ViewBuilder是一个自定义参数属性,它从闭包构造视图。 https://developer.apple.com/documentation/swiftui/viewbuilder
https://developer.apple.com/documentation/swiftui/viewbuilder
Use buildif for optional content when using view builder https://developer.apple.com/documentation/swiftui/viewbuilder/buildif(_:)使用视图构建器https://developer.apple.com/documentation/swiftui/viewbuilder/buildif(_:)时将 buildif用于可选内容
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
:不是一个有效的语法:你需要指定一个
var
,在这种情况下你不需要说@escaping
:
@ViewBuilder var content: (SwiperElement, SwiperItemResource, Dragging) -> Content
or define a func
, where you can say the closure is @escaping
:或定义一个
func
,您可以在其中说闭包是@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 .在第一种情况下,您声明一个变量,该变量存储一个名为Closure的类型。 This type has 3 inputs
SwiperElement, SwiperItemResource, Dragging
, and 1 output of type Content
.此类型有 3 个输入
SwiperElement, SwiperItemResource, Dragging
和 1 个Content
类型的 output。
In second case you define a function, which will get a closure as its argument.在第二种情况下,您定义了一个 function,它将获得一个闭包作为其参数。 Keywords
@escaping
means that the closure will outlive the function itself (ie when function returns, it's possible that closure is still running).关键字
@escaping
意味着闭包将比 function 本身寿命更长(即当 function 返回时,闭包可能仍在运行)。
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
, eg as explained here但如果您在谈论可选的 UI 元素,那么您可能需要熟悉 SwiftUI
@State
,例如解释here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.