Swift 4를 사용하면 두 CGPoint
인스턴스 간의 거리를 확인하기 위해 다음 5 개의 플레이 그라운드 코드 중 하나를 선택할 수 있습니다 .
1. Darwin sqrt(_:)
기능 사용
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()
방법
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. 사용 CGFloat
squareRoot()
방법 및 Core Graphics pow(_:_:)
기능
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. Core Graphics hypot(_:_:)
기능 사용
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. Core Graphics hypot(_:_:)
기능 및 CGFloat
distance(to:)
방법 사용
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
.