Skip to content

Instantly share code, notes, and snippets.

@50percentgrey
Created October 21, 2017 17:36
Show Gist options
  • Save 50percentgrey/dbb9d19d5ab938be7b01d20875606171 to your computer and use it in GitHub Desktop.
Save 50percentgrey/dbb9d19d5ab938be7b01d20875606171 to your computer and use it in GitHub Desktop.
Math series: Distance between 2 points
// Pythagorean theorem
// √(x1 - x2)2 + (y1 - y2)2
//
extension CGPoint {
func distance(from point: CGPoint) -> CGFloat {
let xDist = point.x - x
let yDist = point.y - y
return sqrt((xDist * xDist) + (yDist * yDist))
}
}
// or calculating the hypotenuse
extension CGPoint {
func distance(from point: CGPoint) -> CGFloat {
return hypot(x - point.x, y - point.y)
}
}
// usage
let distance: CGFloat = pointA.distance(from: pointB)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment