BatchedCollection - 从 Swift 集合中创建批次

BatchedCollection 是一个库,旨在帮助您将任何 Swift 集合中的元素分组为指定大小的批次。 这对于诸如分页或向仅接受特定最大输入数量的系统(例如 SIMD 向量)提供输入的功能特别有用。

一个批次将集合中的后续元素分组为最大尺寸由您定义的批次。

主要特性

安装

将以下内容添加到您的 Package.swift 文件中

dependencies: [
    .package(url: "https://github.com/berikv/BatchedCollection.git", from: "0.0.2")
]

用法

基本示例

从 Range 创建批次

let batches = (0..<7).batched(by: 3)

batches[0] == 0..<3 // true, because `Range.SubSequence == Range`
batches[2] == 6..<7 // true

从 Array 创建批次

let batches = Array(0..<7).batched(by: 3)

print(Array(batches[0])) // prints "[0, 1, 2]"
print(Array(batches[1])) // prints "[3, 4, 5]"
print(Array(batches[2])) // prints "[6]"

实际示例


旋转木马一次只能容纳这么多人。

想象一下编写一个游乐园模拟器,其中旋转木马一次只允许 34 名游客。 您可以将游客分成 34 人的小组

while parkIsOpen {
    let visitors = await getQueuedCarouselVisitors()
    for batch in visitors.batched(by: 34) {
        await carousel.clear()
        await carousel.board(batch)
        await carousel.run()
    }
}

为了使其工作,carousel.board() 接受一个游客集合

extension Carousel {
    func board(_ passengers: some Collection<Visitors>) async { ... }
}

具体示例

另一个可能有用的例子是源代码重写。 长长的整数列表可能看起来笨拙

let numbers = [3, 48, 23, 32, 55, 50, 71, 14, 93, 43, 66, 25, 9, 35, 59, 40, 45, 75, 88, 35, 62, 17, 16, 74, 32, 35, 39, 37, 4, 97, 67, 49, 95, 50, 9, 14, 85, 79, 24, 78, 85, 72, 1, 79, 1, 53, 39, 1, 48, 74]

一个小的格式化脚本可以通过例如按 8 个一批来提供帮助

let description = numbers
    .batched(by: 8)
    .map { batch in batch
        .map { String(format: "%02d", $0) }
        .joined(separator: ", ")
    }
    .joined(separator: "\n    ")

print("let numbers = [\n    \(description)]") // copy paste the new `let numbers` definition

当数字每行排列 8 个时,列表可以更容易被解析

let numbers = [
    03, 48, 23, 32, 55, 50, 71, 14
    93, 43, 66, 25, 09, 35, 59, 40
    45, 75, 88, 35, 62, 17, 16, 74
    32, 35, 39, 37, 04, 97, 67, 49
    95, 50, 09, 14, 85, 79, 24, 78
    85, 72, 01, 79, 01, 53, 39, 01
    48, 74]

详细解释

batched(by:) 函数扩展了集合类型,以将其元素拆分为指定大小的批次。 这在分块处理大型集合以优化性能或满足某些约束时特别有用。 batched(by:) 的返回类型是 BatchedSubSequence,它本身是原始集合的 Collection.SubSequence 的集合


BatchedSubSequence 的内存布局由一个用于保存批次大小的整数组成,后跟底层集合的内存。

O(1) 实现

batched(by:) 的实现非常高效,创建 BatchedSubSequence 的复杂度为 O(1)。 结合 Swift 的零成本抽象,这意味着 .batched(by:) 在理论上尽可能高效!

贡献

欢迎贡献!

许可证

您可以自由使用此软件(请参阅 License.md)。 如果这对您有用,如果您告诉我,我将不胜感激。