0

Paul Hudson explained how to split a Swift Array into chunks in his article. It works like this:

extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}

and can be used like this:

let numbers = Array(1...100)
let result = numbers.chunked(into: 5)

I wonder if this algorithm could be generalized to make it work for arbitrary collections/sequences, especially Strings. I thought about applying this algorithm to to the protocols Collection or Sequence...

Any ideas?

blackjacx
  • 9,011
  • 7
  • 45
  • 56

0 Answers0