1

How can I convert this array

var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"]

to this

var data = [["a1","a2"],["a3","a4"],["a5","a6"],["a7","a8"],["a9","a10"]]

Opposite is very easy, but I couldn't find solution for this.

John
  • 15
  • 6

1 Answers1

2

You can use this Array extension from HackingWithSwift:

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)])
        }
    }
}

The usage would be like this:

let chunkedData = data.chunked(into: 2) // [["a1","a2"],["a3","a4"],["a5","a6"],["a7","a8"],["a9","a10"]]
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36