Adding object 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 {
func distanceTo(point: Point) -> Double {
let d1 = pow(x - point.x, 2)
let d2 = pow(y - point.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 = p1.distanceTo(p2)
//distance is 1.4142
- Log in to post comments