Thor
Thor

Reputation: 10058

having difficulties understanding complex swift associatedtype declaration

I saw the line of code below at swift github repository

associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection
    = DefaultRandomAccessIndices<Self>

I know that an associatedtype is an type alias for protocols, and i know how to interpret it in simple cases

But can someone please explain to me the line of code i saw from swift github repository?

Upvotes: 2

Views: 81

Answers (1)

Martin R
Martin R

Reputation: 539815

That means that the associated type Indices must conform to _RandomAccessIndexable and BidirectionalCollection, and by default is DefaultRandomAccessIndices<Self> unless declared (or inferred) otherwise (where Self is the actual type adopting the protocol).

Example:

struct MyIndex : Comparable {
    var value : Int16

    static func ==(lhs : MyIndex, rhs : MyIndex) -> Bool {
        return lhs.value == rhs.value
    }
    static func <(lhs : MyIndex, rhs : MyIndex) -> Bool {
        return lhs.value < rhs.value
    }
}

struct MyCollectionType : RandomAccessCollection {

    var startIndex : MyIndex { return MyIndex(value: 0) }
    var endIndex : MyIndex { return MyIndex(value: 3) }

    subscript(position : MyIndex) -> String {
        return "I am element #\(position.value)"
    }

    func index(after i: MyIndex) -> MyIndex {
        guard i != endIndex else { fatalError("Cannot increment endIndex") }
        return MyIndex(value: i.value + 1)
    }
    func index(before i: MyIndex) -> MyIndex {
        guard i != startIndex else { fatalError("Cannot decrement startIndex") }
        return MyIndex(value: i.value - 1)
    }
}

let coll = MyCollectionType()
let i = coll.indices
print(type(of: i)) // DefaultRandomAccessIndices<MyCollectionType>

MyCollectionType is a (minimal?) implementation of a RandomAccessCollection, using a custom index type MyIndex. It does not define its own indices method or Indices type, so that Indices becomes the default associated type, and indices is a default protocol extension method of RandomAccessCollection.

Upvotes: 1

Related Questions