Created
September 21, 2018 03:46
-
-
Save guzhenhuaGitHub/a0a6d1ca1c3f1f69b96d40714f7fc3fe to your computer and use it in GitHub Desktop.
helper like ruby's Enumerable#each_slice
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
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