Swift 运算符重载

加减乘除重载

在对应的结构,类,枚举里重写即可。

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

Equatable,Comparable

Equatable 设定对象可以比较是否相等。重写 == 运算符。 Comparable 设定对象可以比较大小。重写 >, <, >=, <= 等运算符。

自定义运算符(Custom Operator)

可以自定义新的运算符:在全局作用域使用operator进行声明。

prefix operator 前缀运算符 postfix operator 后缀运算符

//前后运算符,自定义 +++ 为整型加2
prefix operator +++
postfix operator ++-
prefix func +++ (_ i: inout Int) {
    i += 2
}
postfix func ++- (_ i: inout Int) {
    i -= 2
}
var age = 10
+++age
print(age) // 12
age++-
print(age) // 10


//中缀运算符,也就是放置在两个变量中间的运算符,可以定义它的运算优先级
infix operator 中缀运算符:优先级组 
precedencegroup 优先级组 
{ 
associativity: 结合性(left\right\none 
higherThan: 比谁的优先级更高 
lowerThan: 比谁的优先级低 
assignment: true代表在可选链操作中拥有跟赋值运算符一样的优先级 
}

样例代码:

//声明自定义的中缀运算符,名称为 PlusMinusPrecedence
infix operator +-: PlusMinusPrecedence
//定义该运算符的优先级
precedencegroup PlusMinusPrecedence {
    /***
     left: 从左往右执行,可以多个进行结合
     right: 从右往左执行,可以多个进行结合
     none: 不支持多个结合  比如 p1 +- p2 +- p3 就会报错
     */
    associativity: none
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
    assignment: true
}
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)
    }
}
print(Point(x: 10, y: 20) +- Point(x: 5, y: 10)) // Point(x: 15, y: 10)