Skip to content

Instantly share code, notes, and snippets.

@sumitokamoi
Created October 18, 2019 08:45
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumitokamoi/22b8f30c2c1a3ef93cb1f03d4a7e8066 to your computer and use it in GitHub Desktop.
Save sumitokamoi/22b8f30c2c1a3ef93cb1f03d4a7e8066 to your computer and use it in GitHub Desktop.
Swiftで配列をn個の要素に分割する
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