通用LazyCollection类型 [英] Generic LazyCollection type

查看:182
本文介绍了通用LazyCollection类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数,该函数返回由各种组合的生成器函数(例如filter和map)组成的惰性生成器.例如,如果我要应用lazy.filter().map(),则代码如下:

I need a function that returns a lazy generator of various composed generator functions such as filter and map. For example, if I want to apply lazy.filter().map() the code looks like:

// 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>类似的类型.

Is there a more generic way to specify the LazyMapCollection<LazyFilterCollection<MyComplexCollection>, Int>? I tried LazyGenerator<MyComplexCollection> but I'm getting type incompatibility error. Chaining more lazy functions would make the type even more complex. Better and more appropriate for my needs would be to have a type similar to just LazySomething<MyComplexType>.

推荐答案

是!

您想要的东西存在,甚至有一个奇特的名字:"type-erasure"

What you want exists, and even has a fancy name: "type-erasure"

Swift有一些结构可以转发呼叫,但不公开(尽可能多的)底层类型:

Swift has some structs that exist to forward calls on, but not expose (as much of) the underlaying type:

  • 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)的呼叫,因此保留了惰性,这有时是好事,有时是坏事)

(because your call to say subscript(2) is forwarded the laziness is preserved, which is sometimes good, sometimes bad)

但是,AnyForwardCollection在实践中可能会更好,因为它会丢失许多在使用惰性集合时使人们绊倒的方法.

However AnyForwardCollection might work out better in practice because it will be missing many of the methods that trip people up when using lazy collections.

这篇关于通用LazyCollection类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆