find the slope between two points in swift

To find the slope of a line between two points, we can use the formula:

m = (y2 - y1) / (x2 - x1)

where m is the slope, (x1, y1) and (x2, y2) are the two points.

In Swift, we can use the CGPoint struct to represent a point. Here's an example function that takes two CGPoints and returns the slope:

main.swift
func slope(from startPoint: CGPoint, to endPoint: CGPoint) -> CGFloat {

    let deltaX = endPoint.x - startPoint.x
    let deltaY = endPoint.y - startPoint.y

    if deltaX == 0 {
        // vertical line
        return .infinity
    }

    return deltaY / deltaX
}
267 chars
13 lines

We calculate the difference in x and y coordinates between the two points, and return the deltaY / deltaX ratio as the slope. If deltaX is zero (i.e. the line is vertical), we return infinity as the slope.

gistlibby LogSnag