测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可 | MIT |
发布最新发布 | 2017年11月 |
SwiftSwift 版本 | 4.0 |
SPM支持 SPM | ✗ |
由 Oleksii Horishnii 维护。
每个人都知道懒序列,这不是新的。但是,所谓的生成序列是什么意思呢?
GeneratedSeq 是一个用于封装闭包 countFn
和 generateFn
的好包装。它不会存储从这些函数获取的任何值,只提供更多的人性化接口(您可以将其视为 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 文件。