arr.split(size:)

extension Array {
    // โญ๏ธ array.chunked(size:)
    func split(size: Int) -> [[Element]] {
        stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

[
    Array(1...23).split(size: 5),     // 1.
    Array(0..<0).split(size: 5),      // 2.
    
].forEach { print($0) }

// 1. [
//     [ 1,  2,  3,  4,  5], 
//     [ 6,  7,  8,  9, 10], 
//     [11, 12, 13, 14, 15], 
//     [16, 17, 18, 19, 20], 
//     [21, 22, 23]
//    ]
//
// 2. [ ]   // empty array of type [[Int]]

Last updated