LazySeq 0.7.2

LazySeq 0.7.2

测试已测试
语言语言 SwiftSwift
许可 MIT
发布最新发布2017年11月
SwiftSwift 版本4.0
SPM支持 SPM

Oleksii Horishnii 维护。



LazySeq 0.7.2

  • 作者
  • Oleksii Horishnii

LazySeq & GeneratedSeq



每个人都知道懒序列,这不是新的。但是,所谓的生成序列是什么意思呢?

GeneratedSeq 是一个用于封装闭包 countFngenerateFn 的好包装。它不会存储从这些函数获取的任何值,只提供更多的人性化接口(您可以将其视为 Sequence 或 Collection)。它将在每次调用时使用 generateFn 来获取那些索引的项。

LazySeq 是 GeneratedSeq 的子类,实际上将计算出的值保存到 storage 索引-值字典(可用于查找)中。下次查找发生时,将使用已保存的值,而无需重新评估。要强制重新评估,您可以使用 resetStorage 方法。

示例

让我们试一试!

let seq = GeneratedSeq(count: { () -> Int in
                    return 5
                }, generate: { (idx, _) -> String? in
                    guard (idx < 5) else {
                        return nil
                    }
                    return "item\(idx)"
                })

seq // GeneratedSeq<String>
seq[2] // "item2"
seq[2..<5] // ["item2", "item3", "item4"]
seq[5] // crash, index out of range
seq.get(0) // Optional("item0")
seq.get(5) // nil

问题:为什么生成返回可选值,而非可选序列是被创建的?

答案:有时,您可能无法创建超过某个索引的项,但这并不表示序列会被损坏,因为计数函数将限制我们只返回非空结果。

另一方面,.map 函数在转换时不会返回可选值,因为 您可以保证第一个地方就有项,且永远不会越界。

问题:生成闭包的第二参数发生了什么?

答案:当我们用 .get(idx: context:) 函数取得我们的值时,我们可以向生成函数传递任何东西。

let seq = GeneratedSeq(count: { () -> Int in
                    return 5
                }, generate: { (idx, context) -> String in
                    return "item\(idx) with context \(context)"
                })
seq[2] // "item2 with context nil"
seq.get(2, [3, 4]) // "item2 with context [3, 4]"

您还可以向上下文传递闭包 :)

特殊奥运会

斐波那契!

var seq: LazySeq<Int>! // so we can reference it inside
seq = LazySeq(count: nil, generate: { (idx, _) -> Int in
    if idx <= 1 {
        return 1
    }
    return seq[idx-1]+seq[idx-2]
})

seq.prefix(10) // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
seq[10..<15] // [89, 144, 233, 377, 610]

安装

LazySeq 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile
即可。

pod 'LazySeq'

致谢

Oleksii Horishnii,[email protected]

许可

LazySeq 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。