Swift:从两个数组转换为数据集以用于图表
Swift: convert from two arrays to dataset for using in charts
我有两个双数组:
x = [(1.0, 2.0, 3.0, 4.0, 5.0)]
y = [(3.0, 4.0, 5.0, 6.0, 7.0)]
我想在此代码行中使用这些变量 x
和 y
(而不是固定值):
(chartPoints: [(2.0, 2.6),....], color: UIColor.redColor())
我怎样才能将它们组合起来,这样我就有了 [(Double, Double)]
类型的东西?
我不确定我是否正确理解了你的问题,但可以创建一个 CGPoint
s:
的数组
let a: Array<CGFloat> = [1, 2, 3]
let b: Array<CGFloat> = [6, 7, 8]
var c = Array<CGPoint>()
for i in 0..<a.count {
if i < b.count {
c.append(CGPointMake(a[i], b[i]))
}
}
正如@Hamish 建议的那样,您可以简单地执行以下操作:
let pointArr = Array(zip(x, y))
或者你可以这样做:
给定双数组:
x : [Double] = [1.0, 2.0, 3.0, 4.0, 5.0]
y : [Double] = [3.0, 4.0, 5.0, 6.0, 7.0]
要将这些组合成 (Double, Double)
的数组,您可以这样做:
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
}
}
然后使用它:
(chartPoints: pointArr, color: UIColor.redColor())
我有两个双数组:
x = [(1.0, 2.0, 3.0, 4.0, 5.0)]
y = [(3.0, 4.0, 5.0, 6.0, 7.0)]
我想在此代码行中使用这些变量 x
和 y
(而不是固定值):
(chartPoints: [(2.0, 2.6),....], color: UIColor.redColor())
我怎样才能将它们组合起来,这样我就有了 [(Double, Double)]
类型的东西?
我不确定我是否正确理解了你的问题,但可以创建一个 CGPoint
s:
let a: Array<CGFloat> = [1, 2, 3]
let b: Array<CGFloat> = [6, 7, 8]
var c = Array<CGPoint>()
for i in 0..<a.count {
if i < b.count {
c.append(CGPointMake(a[i], b[i]))
}
}
正如@Hamish 建议的那样,您可以简单地执行以下操作:
let pointArr = Array(zip(x, y))
或者你可以这样做:
给定双数组:
x : [Double] = [1.0, 2.0, 3.0, 4.0, 5.0]
y : [Double] = [3.0, 4.0, 5.0, 6.0, 7.0]
要将这些组合成 (Double, Double)
的数组,您可以这样做:
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
}
}
然后使用它:
(chartPoints: pointArr, color: UIColor.redColor())