通用LazyCollection类型

时间:2015-10-28 04:07:56

标签: swift collections lazy-sequences swift2.1

我需要一个函数来返回各种组合生成器函数(如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>的类型。

1 个答案:

答案 0 :(得分:2)

是!

你想要什么,甚至有一个奇特的名字:“type-erasure”

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

  • AnyBidirectionalCollection
  • AnyBidirectionalIndex
  • AnyForwardCollection
  • AnyForwardIndex
  • AnyGenerator
  • AnyRandomAccessCollection
  • AnyRandomAccessIndex
  • AnySequence

所以你想要像

这样的东西
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)被转发,懒惰被保留,这有时是好的,有时是坏的)

然而,AnyForwardCollection在实践中可能会更好,因为它会丢失许多在使用延迟集合时绊倒人的方法。