Created
October 18, 2019 08:45
-
-
Save sumitokamoi/22b8f30c2c1a3ef93cb1f03d4a7e8066 to your computer and use it in GitHub Desktop.
Swiftで配列をn個の要素に分割する
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 chunked(by chunkSize: Int) -> [[Element]] { | |
return stride(from: 0, to: self.count, by: chunkSize).map { | |
Array(self[$0..<Swift.min($0 + chunkSize, self.count)]) | |
} | |
} | |
} | |
let arr = [0,1,2,3,4,5,6,7,8,9] | |
print(arr.chunked(by: 2)) // [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] | |
print(arr.chunked(by: 3)) // [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment