Last active
August 10, 2023 21:35
-
-
Save igorleonovich/12b333fbc5746e9c1866c90ea59ffe3d to your computer and use it in GitHub Desktop.
Slicing arrays by specified slice size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: