使用 { ... in } 的 Swift 闭包语法 [英] Swift closure syntax using { ... in }

查看:31
本文介绍了使用 { ... in } 的 Swift 闭包语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 Apple SwiftUI 教程:绘制路径和形状,显示如下语法:

On the Apple SwiftUI Tutorial: Drawing Paths and Shapes, the following syntax is shown:

struct Badge: View {
    var body: some View {
        GeometryReader { geometry in
            Path { path in
            ...
            }
            .fill(Color.black)
        }
    }
}

我在 关于结构的 Swift 文档中没有看到语法 并感到很困惑.

I did not see the syntax in the Swift docs on structs and feel very confused.

此外,人们怎么可能知道geometry在"GeometryReader 语句中,无论这意味着什么?

Additionally, how might one know that geometry is "in" the GeometryReader statement, whatever that means?

推荐答案

这是尾随闭包的简化语法,所以

This is simplified syntax of trailing closure, so

Path { path in
...
}

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

使用的Path构造函数

/// Initializes to an empty path then calls `callback` to add
/// the initial elements.
public init(_ callback: (inout Path) -> ())

顺便说一句,这个语法在 SwiftUI 中被广泛使用,所以你会在 VStack { .. }, GeometryReader { g in ... } 中看到相同的, ScrollView { ... } 以及 SwfitUI 框架的几乎所有其他 UI 元素.

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.

这篇关于使用 { ... in } 的 Swift 闭包语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆