Matt Spoon
Matt Spoon

Reputation: 2830

programatically making a 2d array in swift

I need to use a for loop to create a 2d array. So far "+=" and .append have not yielded any results. Here is my code. Please excuse the rushed variable naming.

let firstThing = contentsOfFile!.componentsSeparatedByString("\n")

var secondThing: [AnyObject] = []

for i in firstThing {
    let temp = i.componentsSeparatedByString("\"")
    secondThing.append(temp)
}

The idea is that it takes the contents of a csv file, then separates the individual lines. It then tries to separate each of the lines by quotation marks. This is where the problem arises. I am successfully making the quotation separated array (stored in temp), however, I cannot make a collection of these in one array (i.e. a 2d array) using the for loop. The above code generates an error. Does anybody have the answer of how to construct this 2d array?

Upvotes: 0

Views: 234

Answers (1)

Fogmeister
Fogmeister

Reputation: 77631

You can do this using higher order functions...

let twoDimensionalArray = contentsOfFile!.componentsSeparatedByString("\n").map{
    $0.componentsSeparatedByString("\"")
}

The map function takes an array of items and maps each one to another type. In this I'm mapping the strings from the first array into an array pf strings and so creating a 2d array.

This will infer the type of array that is created so no need to put [[String]].

Here you go...

enter image description here

Upvotes: 1

Related Questions