ios - 如何在 Swift 中合并和格式化数组? (X 和 Y 坐标数组)

标签 ios arrays swift merge append

我正在尝试以特定格式合并两个数组,以创建将用于创建图形的 x 和 y 坐标数组。我有单独的 [Double] 格式的 X 值和 Y 值数组,例如:

var xAxis = [1, 2, 3, 4]
var yAxis = [2, 3, 4, 5]

我希望将它们合并为以下格式:

var chartPoints = [(1,2),(2,3),(3,4),(4,5)]

或更一般地说:

chartPoints = [(x,y)]

我已经尝试了几个不同的选项,例如 append 和 extend 方法,但没有成功,因为这不会按照所需的方法对数组进行排序或格式化。

如何将两个 x 轴和 y 轴数组合并为一个单一格式的数组?

最佳答案

您可以使用 zip 全局函数,给定 2 个序列,返回一个元组序列:

let pointsSequence = zip(xAxis, yAxis)

然后您可以使用适当的 init 获取元组数组:

let chartPoints = Array(pointsSequence)

数组的每个元素都是一个 (x, y) 元组 - 但值未命名,因此您可以通过索引访问它们的各个值:

let point = chartPoints[0]
point.0 // This is the 1st element of the tuple
point.1 // This is the 2nd element of the tuple

如果你喜欢命名元组值,你可以使元组类型显式:

let chartPoints: [(x: Int, y: Int)] = Array(pointsSequence)

然后您可以使用索引(如上例所示)或使用它们的显式名称进行访问:

let point = chartPoints[0]
point.x
point.y

关于ios - 如何在 Swift 中合并和格式化数组? (X 和 Y 坐标数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716597/

相关文章:

iOS : Detect SIRI Device

javascript - 合并两个对象数组,同时对特定键求和

ios - dismissViewControllerAnimated() 不会关闭 View Controller

objective-c - 错误 : using bridging headers with framework targets is unsupported

java - 如何在 Java 8 中使用过滤器忽略 int 数组中的值并收集

swift - 如何在 Swift 中从 n 元素数组生成所有可能的 k 元素数组

ios - 如何让 CC2541 在广告数据中包含 kCBAdvDataServiceUUID

iOS - 为什么需要 init 和其他 init 问题

ios - Apptentive Message 单元格颜色变化

arrays - 将 Array{Array{Float64},1} 转换为 Array{Float64,2} 的最佳方法,反之亦然