Swift Swift - 4 months ago 11
Swift Question

How to separately access only Y coordinates of CGPoints in Swift Array?

I've got an array of 20 CGPoints. How to access just Y coordinates of every CGPoint in the array?

Answer
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.
}

Or you may use .enumerate() syntax.

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.
}

If you want an array of all the y coordinates then you can use a nice one liner in swift.

let arrayOfYCoordinates : [CGFloat] = arrayOfPoints.map { $0.y }

Or pass in each y coordiante to the same function.

arrayOfPoints.map { myFunction($0.y) }