Swift|Swift 数组分组

extension Sequence { func clump(by clumpsize:Int) -> [[Element]] { let slices : [[Element]] = self.reduce(into:[]) { memo, cur in if memo.count == 0 { return memo.append([cur]) } if memo.last!.count < clumpsize { memo.append(memo.removeLast() + [cur]) } else { memo.append([cur]) } } return slices } }

【Swift|Swift 数组分组】let arr = [1, 2, 3, 4, 5]
arr.clump(by:2)
// [[1, 2], [3, 4], [5]]

    推荐阅读