【发布时间】:2017-04-01 20:37:37
【问题描述】:
我正在尝试编写自己的IndexingIterator 版本以增加我对Sequence 的理解。我没有在我的结构中为 associatetype Iterator 分配任何类型。但是,编译器并没有抱怨这一点,我得到了makeIterator 的默认实现。
以下是我的代码:
struct __IndexingIterator<Elements: IndexableBase>: Sequence, IteratorProtocol {
mutating func next() -> Elements._Element? {
return nil
}
}
let iterator = __IndexingIterator<[String]>()
// this works and returns an instance of __IndexingIterator<Array<String>>. why?
iterator.makeIterator()
我认为Sequence 上必须有一些扩展,它们添加了默认实现。因此,我在Sequence.swift 中搜索了它,只找到了这个。
extension Sequence where Self.Iterator == Self, Self : IteratorProtocol {
/// Returns an iterator over the elements of this sequence.
public func makeIterator() -> Self {
return self
}
}
我以为会是这样的:
extension Sequence where Self: IteratorProtocol {
typealias Iterator = Self
...
}
我是否遗漏了什么或者我误解了扩展程序?
【问题讨论】:
标签: swift swift3 sequence swift-protocols