Alessandro
Alessandro

Reputation: 4100

2D Arrays in Swift 3

I am trying to populate an array with graph coordinates x and y. At the moment this is what I have:

let chartPoints1 = [(1, 1), (2, 2), (3, 3), (4, 4)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))}

However, I want to add the coordinates from another array by looping through that array, something like this:

let tasks = DatabaseManager.getTasks("Tasks")
let count: Int! = tasks?.count
for i in 1...count {
   chartPoints1.append(i, tasks[i].date)
}

but I can't seem to figure out exactly what kind of array chartPoints1 is and how the map function works.

Upvotes: 0

Views: 130

Answers (1)

Connor Neville
Connor Neville

Reputation: 7351

You don't have a 2d array. You first have an array of tuples, which gets mapped to an array of ChartPoints. So, in your append, I think you're looking for something like

chartPoints1.append(ChartPoint(...))

To clarify further, a 2d array is an array of arrays, which might look like:

[[1, 1], [2, 2], [3, 3]]

Each element of your array is a tuple. So, when you call map, $0 represents the current tuple (say, for instance, (1, 1)). Tuple syntax lets you get the first thing in the tuple by $0.0, the second thing by $0.1 and so forth. With that in mind, I think you should be able to see how you're constructing a ChartPoint with each element, so your new array has type [ChartPoint].

Upvotes: 2

Related Questions