Skip to content

Instantly share code, notes, and snippets.

@aaronvegh
aaronvegh / splitBy.swift
Last active April 24, 2017 20:22 — forked from shsteven/splitBy.swift
Swift: split array by chunks of given size
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
extension Array {
func splitBy(subSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: subSize).map { startIndex in
if let endIndex = self.index(startIndex, offsetBy: subSize, limitedBy: self.count) {
return Array(self[startIndex ..< endIndex])
}
return Array()
}