我想写我自己的IndexingIterator
版本来增加我对Sequence
的理解。我没有在我的结构中分配任何类型到associatetype Iterator。然而,编译器并没有抱怨,我得到了makeIterator
的默认实现。符合Swift中的Sequence和IteratorProtocol
以下是我的代码:
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
...
}
我错过了什么或者我误解了延期?
任何人都可以帮忙吗? – Evan