问题
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