微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

符合Swift中的Sequence和IteratorProtocol

我正在尝试编写自己的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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐