What you are trying to do is called a transposition. Turning an array that looks like:
[[1, 2, 3], [4, 5, 6]]
into an array that looks like:
[[1, 4], [2, 5], [3, 6]]
To do this, let's define a generic function for transposition and apply it to your problem
// Import the text file from the bundle
guard
let inputURL = NSBundle.mainBundle().URLForResource("input", withExtension: "txt"),
let input = try? String(contentsOfURL: inputURL)
else { fatalError("Unable to get data") }
// Convert the input string into [[String]]
let strings = input.componentsSeparatedByString("
").map { (string) -> [String] in
string.componentsSeparatedByString(":")
}
// Define a generic transpose function.
// This is the key to the solution.
public func transpose<T>(input: [[T]]) -> [[T]] {
if input.isEmpty { return [[T]]() }
let count = input[0].count
var out = [[T]](count: count, repeatedValue: [T]())
for outer in input {
for (index, inner) in outer.enumerate() {
out[index].append(inner)
}
}
return out
}
// Transpose the strings
let results = transpose(strings)
You can see the results of the transposition with
for result in results {
print("(result)")
}
Which generates (for your example)
["AYGA", "AYLA", "AYMD"]
["GKA", "LAE", "MAG"]
["GOROKA", "", "MADANG"]
["GOROKA", "LAE", "MADANG"]
["PAPUA NEW GUINEA", "PAPUA NEW GUINEA", "PAPUA NEW GUINEA"]
["06", "00", "05"]
["04", "00", "12"]
["54", "00", "25"]
["S", "U", "S"]
["145", "00", "145"]
["23", "00", "47"]
["30", "00", "19"]
["E", "U", "E"]
["5282", "0000", "0020"]
This has the advantage of not depending on the number of arrays that you have, and the number of subarrays is taken from the count of the first array.
You can download an example playground for this, which has the input as a file in the playground's resources.