Skip to content

Instantly share code, notes, and snippets.

@guzhenhuaGitHub
Created September 21, 2018 03:46
Show Gist options
  • Save guzhenhuaGitHub/a0a6d1ca1c3f1f69b96d40714f7fc3fe to your computer and use it in GitHub Desktop.
Save guzhenhuaGitHub/a0a6d1ca1c3f1f69b96d40714f7fc3fe to your computer and use it in GitHub Desktop.
helper like ruby's Enumerable#each_slice
extension Array {
func eachSlice(_ step: Int) -> [[Element]] {
return stride(from: 0, through: count, by: step)
.lazy
.map { from in
let to = Swift.min(from + step, count)
return (from..<to)
.lazy
.map { [self[$0]] }
.reduce([], +)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment