简体   繁体   English

Swift 闭包语法使用 { ... in }

[英]Swift closure syntax using { … in }

On the Apple SwiftUI Tutorial: Drawing Paths and Shapes , the following syntax is shown:Apple SwiftUI 教程:绘制路径和形状中,显示了以下语法:

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.我没有看到Swift 文档中关于结构的语法,感到很困惑。

Additionally, how might one know that geometry is "in" the GeometryReader statement, whatever that means?此外,如何知道geometryGeometryReader语句“中”,无论这意味着什么?

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之前的变量名是闭包的输入参数。

In the context of SwiftUI, that closure is actually a ViewBuilder , which is a specific type of a function builder.在 SwiftUI 的上下文中,该闭包实际上是ViewBuilder ,它是 function 构建器的特定类型。 You can read more about function readers and the other syntactic sugars that made SwiftUI possible here .您可以在此处阅读有关 function 阅读器和其他使 SwiftUI 成为可能的语法糖的更多信息。

You can learn the type of the closure input argument(s) by option clicking on them in Xcode, just like any other variables.您可以通过在 Xcode 中单击选项来了解闭包输入参数的类型,就像任何其他变量一样。 Or you can check the documentation of GeometryReader to learn what input arguments its closure accepts.或者您可以查看GeometryReader的文档以了解其闭包接受的输入 arguments。

This is simplified syntax of trailing closure, so这是尾随闭包的简化语法,所以

Path { path in
...
}

is just the same as

Path( { (path) in
...
})

of used Path constructor使用的Path构造函数

/// 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.顺便说一句,这种语法在 SwiftUI 中被广泛使用,所以你会在VStack {.. }GeometryReader { g in... }ScrollView {... }和几乎所有其他 SwfitUI 框架的 UI 元素中看到相同的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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