这意味着相关联的类型Indices
必须符合 _RandomAccessIndexable
和BidirectionalCollection
,缺省情况下为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
成为默认相关联的类型, 和 indices
是RandomAccessCollection
默认协议扩展方法。
你的答案是一如既往的惊人和真棒!许多许多非常感谢! – Thor