Custom operators overloading in Swift
Forums:
class Point {
var x: Double
var y: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
}
}
infix operator ^ {}
//global function
func ^ (p: Point, power: Double) -> Point {
let x = pow(p.x, power)
let y = pow(p.y, power)
return Point(x: x, y: y)
}
postfix operator ^ {}
//global function
func ^ (inout p: Point) -> Point {
let x = pow(p.x, p.x)
let y = pow(p.y, p.y)
p = Point(x: x, y: y)
return p
}
var p1 = Point(x: 2, y: 3)
p1 = p1 ^ 3
//p1.x is 8.0 and p1.y is 27.0
var p2 = Point(x: 2, y: 3)
p2^
//p2.x is 4.0 and p2.y is 27.0
- Log in to post comments