0

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?

6
  • for a 2D array you would hav to declare secondThing as [[AnyObject]] Commented Jun 20, 2015 at 12:33
  • secondThing needs to be declared as var if you want to modify it Commented Jun 20, 2015 at 12:36
  • And while you're at it, you might as well be more explicit about what secondThing contains: var secondThing: [[String]] = []. It is an array of array of String. Commented Jun 20, 2015 at 12:41
  • Although I made a mistake with the let, var declaration for secondThing, adding extra square brackets around the the type declaration fixed my problem. Thanks guys! Commented Jun 20, 2015 at 12:52
  • Although I made a mistake with the let, var declaration for secondThing, adding extra square brackets around the type declaration fixed my problem. Thank you! Commented Jun 20, 2015 at 12:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.