Last active
July 18, 2022 19:23
-
-
Save codelynx/703ce6f0441a0b1f28f0dc48686e6761 to your computer and use it in GitHub Desktop.
Array extension to slice an array with given number
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 | |
public extension Array { | |
func slice(count: Int) -> [some Collection] { | |
let n = self.count / count // quotient | |
let i = n * count // index | |
let r = self.count % count // remainder | |
let slices = (0..<n).map { $0 * count }.map { self[$0 ..< $0 + count] } | |
return (r > 0) ? slices + [self[i..<i + r]] : slices | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment