0

In apple's implementation of Identifiable

the required function is

associatedtype ID
var id: Self.ID { get }

why is self required? What is the difference between that and

associatedtype ID
var id: ID { get }
erotsppa
  • 14,248
  • 33
  • 123
  • 181

1 Answers1

1

I think this is just a convention Apple uses when writing their documentation. They write all their associated types with the Self. prefix. Examples: 1, 2, 3. This is so that it is clear what is an associated type, and what isn't. If the declaration for Identifiable.id has instead been written like:

var id: ID { get }

To someone who's never used SwiftUI before, it is unclear whether ID is an entirely separate, top-level type, or an associated type. If it said Self.ID, however, it is clear that ID is an associated type of a protocol.

Other than that, the Self. prefix does not mean anything special. It's just like the self. prefix when referring to a instance member. It is optional in most cases. Just like the self. prefix, you probably need Self. to resolve name conflicts in some situations, though I can't think of any right now.

Apple also seems to have a convention for nested types - to always write out OuterTypeName.InnerTypeName, when just InnerTypeName is enough. Example:

var keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy
Sweeper
  • 213,210
  • 22
  • 193
  • 313