自定義運(yùn)算符僅能包含這些字符:
<pre>
/ = - + * % < >企孩!& | ^责静。~
</pre>
運(yùn)算符位置:
<pre>
前置運(yùn)算符 prefix
中間運(yùn)算符 infix
后置運(yùn)算符 postfix
</pre>
運(yùn)算符其他配置
<pre>
結(jié)合性 associativity
可取值范圍 left哑舒,right和none
優(yōu)先級 precedence
可取值范圍 0~255
</pre>
系統(tǒng)內(nèi)置運(yùn)算符結(jié)合性質(zhì)及優(yōu)先級
求冪相關(guān)(無結(jié)合,優(yōu)先級160)
<pre>
<< 按位左移(Bitwise left shift)
按位右移(Bitwise right shift)
</pre>
乘除法相關(guān)(左結(jié)合,優(yōu)先級150)
<pre>
* 乘
/ 除
% 求余
&* 乘法口锭,忽略溢出( Multiply, ignoring overflow)
&/ 除法曲楚,忽略溢出(Divide, ignoring overflow)
&% 求余, 忽略溢出( Remainder, ignoring overflow)
& 位與( Bitwise AND)
</pre>
加減法相關(guān)(左結(jié)合, 優(yōu)先級140)
<pre>
- 加
- 減
&+ Add with overflow
&- Subtract with overflow
| 按位或(Bitwise OR )
^ 按位異或(Bitwise XOR)
</pre>
Range (無結(jié)合,優(yōu)先級 135)
<pre>
.. 半閉值域 Half-closed range
... 全閉值域 Closed range
</pre>
類型轉(zhuǎn)換 (無結(jié)合,優(yōu)先級 132)
<pre>
is 類型檢查( type check)
as 類型轉(zhuǎn)換( type cast)
<= 小于等于
大于
= 大于等于
== 等于
!= 不等
=== 恒等于
!== 不恒等
~= 模式匹配( Pattern match)
</pre>
合壤逋佟( Conjunctive) (左結(jié)合,優(yōu)先級 120)
<pre>
&& 邏輯與(Logical AND)
</pre>
析取(Disjunctive) (左結(jié)合,優(yōu)先級 110)
<pre>
|| 邏輯或( Logical OR)
</pre>
三元條件(Ternary Conditional )(右結(jié)合,優(yōu)先級 100)
<pre>
?: 三元條件 Ternary conditional
</pre>
賦值 (Assignment) (右結(jié)合, 優(yōu)先級 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
//中間:計(jì)算N的M次方龙誊,左結(jié)合抚垃,優(yōu)先級為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>