find the distance between two points in swift

To find the distance between two points in Swift, you can use the following formula:

main.swift
distance = ((x2 - x1)² + (y2 - y1)²)
38 chars
2 lines

where x1 and y1 are the coordinates of the first point, and x2 and y2 are the coordinates of the second point.

Here's an example implementation of the formula in Swift:

main.swift
import Foundation

func distanceBetweenPoints(x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
    let deltaX = x2 - x1
    let deltaY = y2 - y1
    let distance = sqrt(deltaX * deltaX + deltaY * deltaY)
    return distance
}

// Example usage
let distance = distanceBetweenPoints(x1: 0, y1: 0, x2: 3, y2: 4)
print(distance) // Output: 5.0
351 chars
13 lines

In this example, the distanceBetweenPoints function takes four arguments (x1, y1, x2, and y2) representing the coordinates of the two points. The function calculates the distance using the formula and returns the result as a Double value. Finally, the function is called with example values and the result is printed to the console.

gistlibby LogSnag