Created
June 11, 2020 00:16
-
-
Save azamsharp/e5fb1df2cfe0ff212f5a70094d4c7c69 to your computer and use it in GitHub Desktop.
Swift Array Chunks
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
let animals = ["π","π","π¦","π¦","π¦","π","π","π¦©","π¦"] | |
extension Array { | |
func chunks(size: Int) -> [ArraySlice<Element>] { | |
var chunks: [ArraySlice<Element>] = [ArraySlice<Element>]() | |
for index in stride(from: 0, to: self.count - 1, by: size) { | |
var chunk = ArraySlice<Element>() | |
let end = index + size | |
if end >= self.count { | |
chunk = self[index..<self.count] | |
} else { | |
chunk = self[index..<end] | |
} | |
chunks.append(chunk) | |
if (end + 1) == self.count { | |
let remainingChunk = self[end..<self.count] | |
chunks.append(remainingChunk) | |
} | |
} | |
return chunks | |
} | |
} | |
print(animals.chunks(size: 4)) // usage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment