Search code examples
arraysmacosswift2cgpoint

How to access only Y coordinates of CGPoints in array?


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


Solution

  • 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 if you are using .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.
    }
    

    Swift makes common for loop operations simple. For example, 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 to pass each y coordiante to the same function.

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