【问题标题】:having difficulties understanding complex swift associatedtype declaration难以理解复杂的快速关联类型声明
【发布时间】:2017-08-30 12:06:42
【问题描述】:
我在swift github repository看到下面的代码行
associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection
= DefaultRandomAccessIndices<Self>
我知道associatedtype 是协议的类型别名,并且我知道如何在简单的情况下解释它
但是有人可以向我解释一下我从 swift github 存储库中看到的代码行吗?
【问题讨论】:
标签:
swift
generics
types
protocols
【解决方案1】:
这意味着关联类型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的默认协议扩展方法。