小编Eva*_*van的帖子

符合Swift中的Sequence和IteratorProtocol

我正在尝试编写自己的版本,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 …
Run Code Online (Sandbox Code Playgroud)

sequence swift swift-protocols swift3

5
推荐指数
1
解决办法
1641
查看次数

标签 统计

sequence ×1

swift ×1

swift-protocols ×1

swift3 ×1