简体   繁体   English

Swift @escaping 参数可选

[英]Swift @escaping params optional

@ViewBuilder content: @escaping (SwiperElement, SwiperItemResource, Dragging) -> Content

I am self-learning swift.我是自学swift。 Please help.请帮忙。

  1. what can I call the name of the above code style?上面代码风格的名字叫什么? Callback, function,..?回调,function,..?
  2. I want to set optional for some cases, how to do that?我想在某些情况下设置可选,该怎么做?
  1. It's kind of callback, called closure , more information here: https://docs.swift.org/swift-book/LanguageGuide/Closures.html这是一种回调,称为closure ,更多信息在这里: https://docs.swift.org/swift-book/LanguageGuide/Closures.ZFC35FDC70D5FC69AD269883A82EZ7
  2. If you want to set optional just adding suffix like SwiperElement?如果要设置可选,只需添加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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM