Mit Swift 4 können Sie einen der 5 folgenden Spielplatzcodes auswählen, um den Abstand zwischen zwei CGPoint
Instanzen zu ermitteln.
1. Verwenden der Darwin- sqrt(_:)
Funktion
import CoreGraphics
func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
let xDistance = lhs.x - rhs.x
let yDistance = lhs.y - rhs.y
return sqrt(xDistance * xDistance + yDistance * yDistance)
}
let point1 = CGPoint(x: -10, y: -100)
let point2 = CGPoint(x: 30, y: 600)
distance(from: point1, to: point2)
2. CGFloat
squareRoot()
Methode verwenden
import CoreGraphics
func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
let xDistance = lhs.x - rhs.x
let yDistance = lhs.y - rhs.y
return (xDistance * xDistance + yDistance * yDistance).squareRoot()
}
let point1 = CGPoint(x: -10, y: -100)
let point2 = CGPoint(x: 30, y: 600)
distance(from: point1, to: point2)
3. Verwenden der CGFloat
squareRoot()
Methode und der Core Graphics- pow(_:_:)
Funktion
import CoreGraphics
func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
return (pow(lhs.x - rhs.x, 2) + pow(lhs.y - rhs.y, 2)).squareRoot()
}
let point1 = CGPoint(x: -10, y: -100)
let point2 = CGPoint(x: 30, y: 600)
distance(from: point1, to: point2)
4. Verwenden der Core Graphics- hypot(_:_:)
Funktion
import CoreGraphics
func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
return hypot(lhs.x - rhs.x, lhs.y - rhs.y)
}
let point1 = CGPoint(x: -10, y: -100)
let point2 = CGPoint(x: 30, y: 600)
distance(from: point1, to: point2)
5. Verwenden der Core Graphics- hypot(_:_:)
Funktion und CGFloat
distance(to:)
-Methode
import CoreGraphics
func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
return hypot(lhs.x.distance(to: rhs.x), lhs.y.distance(to: rhs.y))
}
let point1 = CGPoint(x: -10, y: -100)
let point2 = CGPoint(x: 30, y: 600)
distance(from: point1, to: point2)
CGPoint
s zu ermitteln.