determine if a coordinate is contained between an upper left and lower right bounds in swift

main.swift
func coordinateIsWithinBounds(coordinate: CGPoint, upperLeft: CGPoint, lowerRight: CGPoint) -> Bool {
    return coordinate.x >= upperLeft.x && coordinate.x <= lowerRight.x &&
           coordinate.y >= upperLeft.y && coordinate.y <= lowerRight.y
}

// Usage
let coordinate = CGPoint(x: 10, y: 20)
let upperLeft = CGPoint(x: 5, y: 15)
let lowerRight = CGPoint(x: 15, y: 25)

if coordinateIsWithinBounds(coordinate: coordinate, upperLeft: upperLeft, lowerRight: lowerRight) {
    print("Coordinate is within bounds")
} else {
    print("Coordinate is outside bounds")
}
569 chars
16 lines

This function takes a coordinate as a CGPoint, an upper left point as a CGPoint, and a lower right point as a CGPoint and returns a Bool indicating whether the coordinate is within the bounds defined by the upperLeft and lowerRight points.

It does this by checking each component of the coordinate against each component of the upperLeft and lowerRight points using the >= and <= operators to determine if the coordinate is within the bounds.

The usage section shows an example of how to use this function, passing in the relevant points and printing a message indicating whether the coordinate is within the bounds or not.

gistlibby LogSnag