Swift - 自定义运算符

1,075 阅读2分钟

自定义运算符仅能包含这些字符:

/ = - + * % < >!& | ^。~
 

运算符位置:

前置运算符    prefix
中间运算符    infix
后置运算符    postfix
 

运算符其他配置

结合性        associativity
可取值范围    left,right和none

优先级        precedence
可取值范围    0~255

系统内置运算符结合性质及优先级

求幂相关(无结合,优先级160)
<< 按位左移(Bitwise left shift)
>> 按位右移(Bitwise right shift)
 
乘除法相关(左结合,优先级150)
\* 乘
/ 除
% 求余
&* 乘法,忽略溢出( Multiply, ignoring overflow)
&/ 除法,忽略溢出(Divide, ignoring overflow)
&% 求余, 忽略溢出( Remainder, ignoring overflow)
& 位与( Bitwise AND)
 
加减法相关(左结合, 优先级140)
+ 加
- 减
&+ Add with overflow
&- Subtract with overflow
| 按位或(Bitwise OR )
^ 按位异或(Bitwise XOR)
 

Range (无结合,优先级 135)

.. 半闭值域 Half-closed range
... 全闭值域 Closed range
 
类型转换 (无结合,优先级 132)
       
 is 类型检查( type check)
as 类型转换( type cast)
<= 小于等于
>大于
>= 大于等于
== 等于
!= 不等
=== 恒等于
!== 不恒等
~= 模式匹配( Pattern match)
 
合取( Conjunctive) (左结合,优先级 120)
 && 逻辑与(Logical AND)
 
析取(Disjunctive) (左结合,优先级 110)
|| 逻辑或( Logical OR)
 
三元条件(Ternary Conditional )(右结合,优先级 100)
        
?: 三元条件 Ternary conditional
 
赋值 (Assignment) (右结合, 优先级 90)
= 赋值(Assign)
*= Multiply and assign
/= Divide and assign
%= Remainder and assign
+= Add and assign
-= Subtract and assign
<<= Left bit shift and assign
= Right bit shift and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
&&= Logical AND and assign
||= Logical OR and assign
 

范例

// 前置:返回2的n次方
prefix operator  ^ 

prefix func ^ (vector: Double) -> Double {
    return pow(2, vector)
}

println(^5)  // 32.0

// 后置:返回2次方
postfix operator  ^^ 

postfix func ^^ (vector: Int) -> Int {
    return vector * vector
}

println(5^^)  // 25


//中间:计算N的M次方,左结合,优先级为255
precedencegroup OrGroup {
    associativity: left
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
}

infix operator ^^^ : OrGroup
func ^^^(left: Double, right: Double) -> Double {
    return pow(left, right)
}

println(2 ^^^ 10 - 2 ^^^ 3)  // 1024 - 8 = 1016
// Swift 3
func |||(left: @autoclosure @escaping () -> T, right: @autoclosure @escaping () -> T) -> (Bool) -> T {  
    return { condition in
        if condition {
            return left()
        } else {
            return right()
        }
    }
}

func ???(condition: @autoclosure @escaping () -> Bool, value: (Bool) -> T) -> T {  
    return value(condition())
}

let bTrue = true  
let bFalse = false
 
bTrue ??? "true value" ||| "false value"  
// 输出 true value
bFalse ??? "true value" ||| "false value"  
// 输出 false value