mostworld77 mostworld77 - 3 months ago 15
Swift Question

Swift: convert from two arrays to dataset for using in charts

I have two double arrays:

x = [(1.0, 2.0, 3.0, 4.0, 5.0)]


and

y = [(3.0, 4.0, 5.0, 6.0, 7.0)]


I want to use these variables
x
and
y
in this code line (instead fixed values):

(chartPoints: [(2.0, 2.6),....], color: UIColor.redColor())


but I haven't found a solution to this problem.
Any ideas?

Answer

As @Hamish suggested you can simply do:

let pointArr = Array(zip(x, y))

Or you can do this:

Given the double Arrays:

x : [Double] = [1.0, 2.0, 3.0, 4.0, 5.0]
y : [Double] = [3.0, 4.0, 5.0, 6.0, 7.0]

To combine these into an array of (Double, Double), you'd do this:

let x : [Double] = [1.0, 2.0, 3.0, 4.0, 5.0]
let y : [Double] = [3.0, 4.0, 5.0, 6.0, 7.0]

var pointArr : [(Double, Double)] = [] // Empty array of points that you'll fill below

for index in 0..<x.count { // for all x values
    if index < y.count { // make sure that there aren't more x values than y values
        let newPoint = (x[index], y[index]) // Create a new point
        pointArr.append(newPoint) // Add the point to the array
    }
}

And then to use it:

(chartPoints: pointArr, color: UIColor.redColor())
Comments