You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以更Swifty的方式实现Swift数组的重叠分块?

实现数组的重叠分块

你完全可以用stride结合map来实现更Swifty的重叠分块,核心是调整stride的步长为1,同时控制起始索引范围避免越界。

扩展Array实现通用方法

extension Array {
    func overlappingChunks(ofSize chunkSize: Int) -> [[Element]] {
        // 处理非法输入:块大小必须大于0且不超过数组长度
        guard chunkSize > 0, chunkSize <= count else { return [] }
        // 生成所有合法起始索引,步长1实现重叠
        return stride(from: 0, through: count - chunkSize, by: 1).map { startIndex in
            // 从起始索引取连续chunkSize个元素并转成数组
            Array(self[startIndex..<startIndex + chunkSize])
        }
    }
}

使用示例

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result = input.overlappingChunks(ofSize: 3)
print(result)
// 输出:[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]

原理说明

  • 不重叠分块的stride步长是chunkSize,而重叠分块将步长改为1,让每个块的起始索引比前一个多1,从而实现重叠效果。
  • through: count - chunkSize确保最后一个块的结束索引刚好等于数组长度,不会触发越界错误。

另一种reduce实现方式

如果偏好reduce,也可以用它来累积结果:

extension Array {
    func overlappingChunks(ofSize chunkSize: Int) -> [[Element]] {
        guard chunkSize > 0, chunkSize <= count else { return [] }
        return (0...count - chunkSize).reduce(into: []) { chunks, start in
            chunks.append(Array(self[start..<start + chunkSize]))
        }
    }
}

内容的提问来源于stack exchange,提问作者koen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:57:10