通用 LazyCollection 类型

Generic LazyCollection type

我需要一个函数 returns 各种组合生成器函数(例如过滤器和映射)的惰性生成器。例如,如果我想应用 lazy.filter().map(),代码如下所示:

// Simplified
typealias MyComplexType = Int
typealias MyComplexCollection = [MyComplexType]

func selection() -> LazyMapCollection<LazyFilterCollection<MyComplexCollection>, Int> {
    let objects:MyComplexCollection = [1, 2, 3, 4, 5, 6]
    let result = objects.lazy.filter({[=10=] < 4}).map({[=10=] * 10})

    return result
}

for obj in someObjects() {
    print(obj)
}

是否有更通用的方法来指定 LazyMapCollection<LazyFilterCollection<MyComplexCollection>, Int>?我试过 LazyGenerator<MyComplexCollection> 但出现类型不兼容错误。链接更多惰性函数会使类型更加复杂。更好更适合我的需要的是具有类似于 LazySomething<MyComplexType>.

的类型

是的!

你要的都有,而且还有个花哨的名字:"type-erasure"

Swift 有一些结构可以转发调用,但不会暴露(尽可能多的)底层类型:

  • 任何双向集合
  • AnyBidirectionalIndex
  • AnyForwardCollection
  • AnyForwardIndex
  • 任何发电机
  • 任何随机访问集合
  • AnyRandomAccessIndex
  • 任意序列

所以你想要

func selection() -> AnySequence<MyComplexType> {
    let objects:MyComplexCollection = [1, 2, 3, 4, 5, 6]
    let result = objects.lazy.filter({[=10=] < 4}).map({[=10=] * 10})

    return AnySequence(result)
}

(因为你对 say subscript(2) 的调用被转发了,惰性得以保留,这有时好,有时坏)

但是 AnyForwardCollection 在实践中可能会更好,因为它会缺少许多在使用惰性集合时使人们感到困惑的方法。