swiftswiftuikeypaths

identified(by: \.self) - what does it do?


In this video: https://developer.apple.com/videos/play/wwdc2019/103/, the following snippet of code is shown at around 15:30:

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

What does it do? Where does self points to? The current object (TraitCell_Preview)? It doesn't even compile in my computer since common isn't a member in ContentSizeCategory. I thought I had seen it before in a SwiftUI talk (\.self) . Keypath's aren't my best thing in Swift though.

I understand ForEach's elements needs to be Identifiable. self (a.k.a. TraitCell_Preview right?) does only conform to PreviewProvider so not Identifiable (if the private _PreviewProvider protocol from which PreviewProvider conforms to doesn't conform to Identifiable, not sure about that since I can not see the code).

What is \.self in the snippet of code and where does it points to?


Solution

    1. Looks like common is a static variable that they created to help their demo. It's just an extension on ContentSizeCategory. Something like this:
    extension ContentSizeCategory {
         static var common = [ContentSizeCategory.accessibilityLarge,
                              ContentSizeCategory.accessibilityMedium,
                            ContentSizeCategory.extraSmall]
    
    }
    
    1. ContentSizeCategory is an enum, conforms to Hashable that means every type is uniquely identifiable. Below is the signature of identified function, when it is called you need to tell what's the key path that it should use in order to uniquely identify items. So \.self is basically telling the whole self is unique because it conforms to Hashable.
    func identified<ID>(by getID: KeyPath<Binding<Value.Element>, ID>) -> IdentifierValuePairs<Binding<Value>, ID> where ID : Hashable