Adding type methods using extensions in Swift
Forums:
class Point {
var x: Double
var y: Double
init (x: Double, y:Double) {
self.x = x
self.y = y
}
}
extension Point {
class func getDistance(p1: Point, _ p2: Point) -> Double {
let d1 = pow(p1.x - p2.x, 2)
let d2 = pow(p1.y - p2.y, 2)
return sqrt(d1 + d2)
}
}
let p1 = Point (x: 1.0,y: 2.0)
let p2 = Point (x: 2.0,y: 3.0)
let distance = Point.getDistance(p1, p2)
//distance is 1.4142
- Log in to post comments