0

I'm trying to parse a string into an N × M array of array of characters. For example - given the following:

let string = "ABCDEF" + "GHIJKL" + "MNOPQR"

I'd like to convert to this:

[
  ["A", "B", "C", "D", "E", "F"],
  ["G", "H", "I", "J", "K", "L"],
  ["M", "N", "O", "P", "Q", "R"],
]

I noticed using Array(string.characters) gives me a one dimension array. Does a Swift function exist to group a one dimensional array? Is it possible to convert the string directly into a multi dimensional array?

Stussa
  • 3,375
  • 3
  • 24
  • 35
  • Are you having 3 different string `ABCDEF`, `GHIJKL` and `MNOPQR`. – Nirav D Feb 21 '17 at 06:25
  • @NiravD nope - that's just to show how the split happens - one string. – Stussa Feb 21 '17 at 06:38
  • @Stussa You want to split your string with 6 character range? – Nirav D Feb 21 '17 at 06:39
  • 1
    See http://stackoverflow.com/questions/31185492/split-large-array-in-array-of-two-elements for a quite general solution to split an array into chunks of a given size. – Martin R Feb 21 '17 at 06:45
  • 1
    Using the chunk method from http://stackoverflow.com/a/31185663/1187415 this becomes simply `Array(string.characters.chunk(5))` – Martin R Feb 21 '17 at 08:23

0 Answers0