Swift - 运算符重载

struct Point {
    
    var x = 0, y = 0
    
}

var p1 = Point(x: 10, y: 20)
var p2 = Point(x: 11, y: 22)
let p3 = p1 + p2

在上述代码中,p3是不能这么直接相加的,我们需要重载运算符

func + (p1:Point,p2:Point) -> Point {
    Point(x: p1.x+p2.x, y: p1.y+p2.y)
}

这样就不会报错了
同样也支持多个相加

let p3 = p1 + p2 + p3 
// 可以理解为p1+p2加完后,再加p3

方法建议写在类型里面

struct Point {
    
    var x = 0, y = 0
    static func + (p1:Point,p2:Point) -> Point {
           Point(x: p1.x+p2.x, y: p1.y+p2.y)
    }
    static func - (p1:Point,p2:Point) -> Point {
           Point(x: p1.x-p2.x, y: p1.y-p2.y)
    }
    static func * (p1:Point,p2:Point) -> Point {
           Point(x: p1.x*p2.x, y: p1.y*p2.y)
    }
    static func += (p1: inout Point,p2:Point){
           p1 = p1 + p2
    } // 这个比较特别 += 是不需要返回值

}

你可能感兴趣的:(Swift - 运算符重载)