3

在此视频中:https ://developer.apple.com/videos/play/wwdc2019/103/ ,以下代码片段显示在 15:30 左右:

...
ForEach(ContentSizeCategory.common.identified(by: \.self))
...

它有什么作用?self指向哪里?当前对象 ( TraitCell_Preview)?它甚至无法在我的计算机中编译,因为common它不是ContentSizeCategory. 我以为我以前在一次SwiftUI谈话中看到过它(\.self)。Keypath不过,这并不是我在 Swift 中最好的东西。

我理解ForEach的元素需要Identifiableself(又名TraitCell_Preview对吗?)只符合PreviewProvider所以不符合Identifiable(如果符合的私有_PreviewProvider协议PreviewProvider不符合Identifiable,则不确定,因为我看不到代码)。

代码片段中有什么\.self,它指向哪里?

4

2 回答 2

4
  1. Looks likecommonstatic他们为帮助演示而创建的变量。它只是ContentSizeCategory. 像这样的东西:
extension ContentSizeCategory {
     static var common = [ContentSizeCategory.accessibilityLarge,
                          ContentSizeCategory.accessibilityMedium,
                        ContentSizeCategory.extraSmall]

}
  1. ContentSizeCategory是一个枚举,符合 Hashable,这意味着每种类型都是唯一可识别的。下面是identified函数的签名,当它被调用时,你需要告诉它应该使用什么键路径来唯一标识项目。所以\.self基本上告诉整个自我是独一无二的,因为它符合 Hashable。
func identified<ID>(by getID: KeyPath<Binding<Value.Element>, ID>) -> IdentifierValuePairs<Binding<Value>, ID> where ID : Hashable
于 2019-06-06T01:03:33.943 回答
1

方法self是返回对象本身的属性,例如:

let string = "text"
print(string[keyPath: \.self]) // "text"

我们在访问类型时也使用它,例如Int.self.

我假设整个实例都用作标识符。

于 2019-06-05T21:34:14.613 回答