我一直试图找出以下代码为何含糊不清......
public func product <T1: Sequence, T2: Sequence> (_ sequence1: T1, _ sequence2: T2) ->
AnySequence<(T1.Element, T2.Element)> {
return AnySequence(
sequence1.flatMap { element1 in
sequence2.map { element2 in
(element1, element2)
}
}
)
}
public func product <T1: LazySequenceProtocol, T2: LazySequenceProtocol> (_ sequence1: T1, _ sequence2: T2) ->
LazySequence<AnySequence<(T1.Element, T2.Element)>> {
return AnySequence(
sequence1.flatMap { element1 in
sequence2.map { element2 in
(element1, element2)
}
}
).lazy
}
...当我用两个懒惰的序列调用它并打电话给makeIterator
EXAMPLE时。
_ = product([1, 2].lazy, [3, 4].lazy).makeIterator()
然而,以下代码并没有这种歧义...
public struct Product2Sequence <T1: Sequence, T2: Sequence>: Sequence {
public typealias Element = (T1.Element, T2.Element)
public typealias Iterator = AnyIterator<Element>
private let iterator: Iterator
internal init (_ sequence1: T1, _ sequence2: T2) {
self.iterator = AnyIterator(
sequence1.flatMap { element1 in
sequence2.map { element2 in
(element1, element2)
}
}.makeIterator()
)
}
public func makeIterator () -> Iterator {
return self.iterator
}
}
public struct LazyProduct2Sequence <T1: LazySequenceProtocol, T2: LazySequenceProtocol>: LazySequenceProtocol {
public typealias Element = (T1.Element, T2.Element)
public typealias Iterator = AnyIterator<Element>
private let iterator: Iterator
internal init (_ sequence1: T1, _ sequence2: T2) {
self.iterator = AnyIterator(
sequence1.flatMap { element1 in
sequence2.map { element2 in
(element1, element2)
}
}.makeIterator()
)
}
public func makeIterator () -> Iterator {
return self.iterator
}
}
public func product <T1: Sequence, T2: Sequence> (_ sequence1: T1, _ sequence2: T2) -> Product2Sequence<T1, T2> {
return Product2Sequence(sequence1, sequence2)
}
public func product <T1: LazySequenceProtocol, T2: LazySequenceProtocol> (_ sequence1: T1, _ sequence2: T2) ->
LazyProduct2Sequence<T1, T2> {
return LazyProduct2Sequence(sequence1, sequence2)
}
...当我用两个懒惰的序列调用它并打电话给makeIterator
EXAMPLE时。
_ = product([1, 2].lazy, [3, 4].lazy).makeIterator()
我的理由是,懒惰序列符合LazySequenceProtocol
和Sequence
,因此类型系统不知道选择哪个product
。但按照这个定义,第二个版本也应该不起作用。
我使用的是Swift 4.0。
第二个版本的作用是什么?
答案 0 :(得分:1)
这是一个通过4.1解决的错误(请参见https://bugs.swift.org/browse/SR-4509)。类型求解器以前无法在Sequence
和LazySequenceProtocol
之间进行选择,因为前者显然符合后者。
我不能肯定地说为什么您的第二个版本可以在4.0上运行并且没有证据支持我的假设,但是我想这与类型求解器能够从更具体的回报中获取更多信息有关。类型。
无论如何,LazySequenceProtocol
现在是首选,以便尽可能长时间地保持懒惰。您的代码可以在Swift 4.1中正常工作。