prefix(_ maxLength:) is type-erased when used with a struct that conforms to LazySequenceProtocol

纵然是瞬间 提交于 2020-01-13 15:04:31

问题


prefix(_ maxLength:) returns a type-erased Sequence in the following codeEXAMPLE:

public struct CycleIterator <Base: Sequence>: IteratorProtocol {
  public typealias Element = Base.Element

  private var sequence: Base
  private var iterator: Base.Iterator

  internal init (_ sequence: Base) {
    self.sequence = sequence
    self.iterator = self.sequence.makeIterator()
  }

  public mutating func next () -> Element? {
    var next = self.iterator.next()

    if next == nil {
      self.iterator = self.sequence.makeIterator()
      next = self.iterator.next()
    }

    return next
  }
}

public struct LazyCycleSequence <Base: LazySequenceProtocol>: LazySequenceProtocol {
  public typealias Iterator = CycleIterator<Base>
  public typealias Element = Iterator.Element

  private let base: Base

  internal init (_ base: Base) {
    self.base = base
  }

  public func makeIterator () -> Iterator {
    return Iterator(self.base)
  }
}

public extension LazySequenceProtocol {
  func cycle () -> LazyCycleSequence<Self> {
    return LazyCycleSequence(self)
  }
}

print(type(of: [1, 2, 3].lazy.cycle().prefix(5))) // AnySequence<Int>

This would make any subsequent operations eager. I know I can just add another call to lazy after prefix to get back into lazy land, but that kind of defeats the entire purpose of the lazy property; once we're lazy we should stay lazy.

What could be the reasoning behind this?

来源:https://stackoverflow.com/questions/45842065/prefix-maxlength-is-type-erased-when-used-with-a-struct-that-conforms-to-laz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!