Eva*_*van 5 sequence swift swift-protocols swift3
我正在尝试编写自己的版本,IndexingIterator以加深我对的了解Sequence。我尚未在结构中将任何类型分配给关联类型迭代器。但是,编译器对此并没有抱怨,我得到了的默认实现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()
Run Code Online (Sandbox Code Playgroud)
我认为必须有一些扩展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
}
}
Run Code Online (Sandbox Code Playgroud)
我以为会是这样的:
extension Sequence where Self: IteratorProtocol {
typealias Iterator = Self
...
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?还是我误解了扩展名?
类型别名不是必需的,因为Element关联的类型是从next().
这是一个简单的例子:
protocol ResourceProvider {
associatedtype Resoruce
func provide() -> Resoruce;
}
struct StringProvider {
func provide() -> String { // "Resource" inferred to be "String"
return "A string"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1641 次 |
| 最近记录: |