How to calculate the Euclidean distance between two points in Swift

1 Answer

0 votes
import Foundation

// The Euclidean distance is a measure of the straight-line distance 
// between two points in a 2D or 3D space

// calculateEuclideanDistance computes the Euclidean distance between two 2D points
func calculateEuclideanDistance(x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
}

func main() {
    let x1 = 3.0
    let y1 = 4.0
    let x2 = 5.0
    let y2 = 9.0

    let distance = calculateEuclideanDistance(x1: x1, y1: y1, x2: x2, y2: y2)
    print(String(format: "Euclidean Distance: %.5f", distance))
}


main()


/*
run:

Euclidean Distance: 5.38516

*/

 



answered Oct 13, 2025 by avibootz
...