2017-04-05 99 views
2

遇到困难,我看到了下面的代码行的swift github repository理解复杂的迅速associatedtype声明

associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection 
    = DefaultRandomAccessIndices<Self> 

我知道的associatedtype是协议的类型别名,我知道如何解释它在简单的情况下

但有人可以请向我解释我从swift github存储库中看到的代码行吗?

回答

1

这意味着相关联的类型Indices必须符合 _RandomAccessIndexableBidirectionalCollection,缺省情况下为DefaultRandomAccessIndices<Self>除非声明(或推断),否则(其中Self是采用协议的实际类型)。

实施例:

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是一个(最小的?)实施 RandomAccessCollection的,使用自定义索引类型MyIndex。 它没有定义其自身的indices方法或Indices类型, 使得Indices成为默认相关联的类型, 和 indicesRandomAccessCollection默认协议扩展方法。

+0

你的答案是一如既往的惊人和真棒!许多许多非常感谢! – Thor