如何仅访问数组中 CGPoints 的 Y 坐标?

How to access only Y coordinates of CGPoints in array?

我有一个包含 20 个 CGPoint 的数组。如何只访问数组中每个 CGPoint 的 Y 坐标?

为什么带有 point.y 的简单 foreach 循环不起作用?

var arrayOfPoints : [CGPoint] = [.....]//your array of points

for point in arrayOfPoints {
   let y = point.y
   //You now have just the y coordinate of each point in the array.
}

或者如果您使用的是 .enumerate() 语法。

for (index, point) in arrayOfPoints.enumerate() {
   let y = point.y
   //You now have just the y coordinate of each point in the array.

   print(point.y) //Prints y coordinate of each point.
}

Swift 使常见的 for 循环操作变得简单。例如, 如果你想要一个包含所有 y 坐标的数组,那么你可以在 swift.

中使用一个漂亮的衬垫
let arrayOfYCoordinates : [CGFloat] = arrayOfPoints.map { [=12=].y }

或者传入以将每个 y 坐标传递给相同的函数。

arrayOfPoints.map { myFunction([=13=].y) }

给你

let arrayOfPoints : [CGPoint] = [CGPoint(x: 1, y: 2), CGPoint(x: 3, y: 4)]

let yCoordinates = arrayOfPoints.map { [=10=].y }

for y in yCoordinates {
    print("y = \(y)") //Or whatever you want to do with the y coordinates
}