Skip to content

Instantly share code, notes, and snippets.

@codelynx
Last active July 18, 2022 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codelynx/703ce6f0441a0b1f28f0dc48686e6761 to your computer and use it in GitHub Desktop.
Save codelynx/703ce6f0441a0b1f28f0dc48686e6761 to your computer and use it in GitHub Desktop.
Array extension to slice an array with given number
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