我需要一个函数,它返回各种组合生成器函数(如filter和map)的惰性生成器。例如,如果我想应用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({$0 < 4}).map({$0 * 10})

    return result
}

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

有没有更通用的方法来指定LazyMapCollection<LazyFilterCollection<MyComplexCollection>, Int>?我试过LazyGenerator<MyComplexCollection>但是我得到了类型不兼容错误。链接更多的惰性函数将使类型更加复杂。更好更适合我的需要是有一个类似的类型只是LazySomething<MyComplexType>

最佳答案

对!
你想要的东西,甚至有一个花哨的名字:“类型删除”
SWIFT有一些结构,用于向前调用,但不暴露(多)下层类型:
任意双向集合
任意双向索引
任何转发集合
任意向前索引
任意生成器
任意随机访问集合
任意随机访问索引
任意序列
所以你想要像

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

    return AnySequence(result)
}

(因为你说下标(2)是转发的,所以保持了懒惰,有时好,有时坏)
然而,任何forwardcollection在实践中可能会更好,因为它将丢失许多在使用惰性集合时绊倒人们的方法。

10-05 20:48
查看更多