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]]
Swift Algorithms โฉ Collection โฉ chunks(ofCount:) โญ๏ธ
similar to arr.split(where:).
Last updated