gpt4 book ai didi

swift - SwiftUI 中使用的反斜杠 (\) 是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 21:55:59 24 4
gpt4 key购买 nike

在 SwiftUI 的 Apple 教程“组合复杂接口(interface)”中,该教程使用了一个反斜杠,它似乎不是字符串插值或转义字符。这是一行:

ForEach(categories.keys.sorted().identified(by: \.self))

这个反斜杠的目的是什么?

下面是包含它的整个结构。

struct CategoryHome: View {
var categories: [String: [Landmark]] {
.init(
grouping: landmarkData,
by: { $0.category.rawValue }
)
}

var body: some View {
NavigationView {
List {
ForEach(categories.keys.sorted().identified(by: \.self)) { key in
Text(key)
}
}
.navigationBarTitle(Text("Featured"))
}
}
}

最佳答案

SwiftUI 中,黑斜杠运算符用于引用要在给定 block 内使用的键路径。

来自苹果:

Add the ability to reference the identity key path, which refers to the entire input value it is applied to.

例如,请看这段代码:

ForEach(["iPhone SE", "iPhone XS Max"].identified(by: \.self)) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
}

here 在遍历数组时,使用 self(here - string) 作为键

现在再举一个例子:我们使用对象数组(不是字符串),现在在这种情况下,用作 block 内用于迭代的键的键是 id。

List(landmarkData.identified(by: \.id)) { landmark in
LandmarkRow(landmark: landmark)
}

关于swift - SwiftUI 中使用的反斜杠 (\) 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56489766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com