加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

符合Swift中的Sequence和IteratorProtocol

发布时间:2020-12-14 04:31:27 所属栏目:百科 来源:网络整理
导读:我正在尝试编写自己的IndexingIterator版本以增加对Sequence的理解.我没有在我的struct中为associatetype Iterator指定任何类型.然而,编译器没有抱怨,我得到了makeIterator的默认实现. 以下是我的代码: struct __IndexingIteratorElements: IndexableBase:
我正在尝试编写自己的IndexingIterator版本以增加对Sequence的理解.我没有在我的struct中为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
    ...
}

我错过了什么或者我误解了扩展吗?

解决方法

看起来亚历山大的答案是正确的.这是一个简化版本,不使用序列:

protocol MySequence {
    associatedtype Iterator: IteratorProtocol
    func maakeIterator() -> Iterator
}

extension MySequence where Self.Iterator == Self,Self : IteratorProtocol {
    /// Returns an iterator over the elements of this sequence.
    func maakeIterator() -> Self {
        return self
    }
}

struct __IndexingIterator<Element>: MySequence,IteratorProtocol {
    mutating func next() -> Element? {
        return nil
    }
}

let iterator = __IndexingIterator<[String]>()
iterator.maakeIterator()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读