A quest for Collection's Index definition

From the source code of Index definition, it's simple.
But when I use the Cmd+Click to see the Index definition from xcode, it's totally different:

associatedtype Index : Comparable where Self.Index == Self.Indices.Element, Self.Indices.Element == Self.Indices.Index, Self.Indices.Index == Self.SubSequence.Index, Self.SubSequence.Index == Self.Indices.Indices.Element, Self.Indices.Indices.Element == Self.Indices.Indices.Index, Self.Indices.Indices.Index == Self.SubSequence.Indices.Element, Self.SubSequence.Indices.Element == Self.SubSequence.Indices.Index, Self.SubSequence.Indices.Index == Self.SubSequence.Indices.Indices.Element, Self.SubSequence.Indices.Indices.Element == Self.SubSequence.Indices.Indices.Index

I guess that the compiler should does something, but I can't find any clue from source code of Swift.

Can someone give me a hint?


It depends on where you cmd+click from.
Many of the generic contexts add further constraints to associated type, it’ll likely end up like looking that for very specialized protocol that Xcode infer to.

On further investigation, it seems that it is indeed normal Collection.Index.

To paint a more complete picture, you might want to include other associated types:

protocol Collection {
  associatedtype Index: Comparable
  associatedtype SubSequence: Collection = Slice<Self>
    where SubSequence.Index == Index,
      Element == SubSequence.Element,
      SubSequence.SubSequence == SubSequence
  associatedtype Indices : Collection = DefaultIndices<Self>
    where Indices.Element == Index, 
      Indices.Index == Index,
      Indices.SubSequence == Indices

If you gather all constraints regarding Index, it'd be

SubSequence.Index == Index
Indices.Element == Index
Indices.Index == Index
Indices.SubSequence == Indices

Indices.Indices.Index == Indices.Index // Indices being Collection
and so on...

Which should be able to infer all of the constraints that Xcode found.

1 Like