自定义运算符仅能包含这些字符:
<pre>
/ = - + * % < >!& | ^。~
</pre>
运算符位置:
<pre>
前置运算符 prefix
中间运算符 infix
后置运算符 postfix
</pre>
运算符其他配置
<pre>
结合性 associativity
可取值范围 left,right和none
优先级 precedence
可取值范围 0~255
</pre>
系统内置运算符结合性质及优先级
求幂相关(无结合,优先级160)
<pre>
<< 按位左移(Bitwise left shift)
按位右移(Bitwise right shift)
</pre>
乘除法相关(左结合,优先级150)
<pre>
* 乘
/ 除
% 求余
&* 乘法,忽略溢出( Multiply, ignoring overflow)
&/ 除法,忽略溢出(Divide, ignoring overflow)
&% 求余, 忽略溢出( Remainder, ignoring overflow)
& 位与( Bitwise AND)
</pre>
加减法相关(左结合, 优先级140)
<pre>
- 加
- 减
&+ Add with overflow
&- Subtract with overflow
| 按位或(Bitwise OR )
^ 按位异或(Bitwise XOR)
</pre>
Range (无结合,优先级 135)
<pre>
.. 半闭值域 Half-closed range
... 全闭值域 Closed range
</pre>
类型转换 (无结合,优先级 132)
<pre>
is 类型检查( type check)
as 类型转换( type cast)
<= 小于等于
大于
= 大于等于
== 等于
!= 不等
=== 恒等于
!== 不恒等
~= 模式匹配( Pattern match)
</pre>
合取( Conjunctive) (左结合,优先级 120)
<pre>
&& 逻辑与(Logical AND)
</pre>
析取(Disjunctive) (左结合,优先级 110)
<pre>
|| 逻辑或( Logical OR)
</pre>
三元条件(Ternary Conditional )(右结合,优先级 100)
<pre>
?: 三元条件 Ternary conditional
</pre>
赋值 (Assignment) (右结合, 优先级 90)
<pre>
= 赋值(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
</pre>
范例
<pre>
// 前置:返回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
</pre>
<pre>
// 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
</pre>
网友评论