Skip to content

Instantly share code, notes, and snippets.

@igorleonovich
Last active August 10, 2023 21:35
Show Gist options
  • Save igorleonovich/12b333fbc5746e9c1866c90ea59ffe3d to your computer and use it in GitHub Desktop.
Save igorleonovich/12b333fbc5746e9c1866c90ea59ffe3d to your computer and use it in GitHub Desktop.
Slicing arrays by specified slice size
import Foundation
extension Array where Element: Any {
func sliced(sliceSize: Int) -> [[Element]] {
var result = [[Element]]()
guard count > 0 else { return result }
let slicesCount = Int(ceil(Double(count) / Double(sliceSize)))
for i in 1...slicesCount {
var startIndex = 0
if i > 1 {
startIndex = ((i - 1) * sliceSize)
}
var endIndex = (sliceSize * i) - 1
if endIndex > count - 1 {
endIndex = count - 1
}
result.append(Array(self[startIndex...endIndex]))
}
return result
}
}
@igorleonovich
Copy link
Author

Usage:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
print(array.sliced(sliceSize: 5))
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment