位操作符
非:~
與:&
或:|
異或:^
左移:<<
右移:>>
對于無符號表示和有符號表示,位移行為不一樣。
溢出運算符
Overflow addition (&+)
Overflow subtraction (&-)
Overflow multiplication (&*)
Overflow division (&/)
Overflow remainder (&%)
上溢
0 11111111
&+ 0 00000001
= 1 00000000
= 0
下溢
00000000
&+ 00000001
= 11111111
= 255
for both signed and unsigned integers,
overflow always wraps around from the largest valid integer value back to the smallest,
and underflow always wraps around from the smallest value to the largest.
除0
&/
,&%
除零都返回零。
運算符函數
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
前綴、后綴
添加 prefix
、postfix
修改符。
prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
混合賦值運算符
把左操作數標記為 inout
。
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
prefix func ++ (inout vector: Vector2D) -> Vector2D {
vector += Vector2D(x: 1.0, y: 1.0)
return vector
}
默認的賦值運算符和三元運算符(a ? b : c
) 不能重載。
等號運算符
自定義的類和結構沒有默認的等號比較運算。
自定義運算符
[prefix/infix/postfix] operator [opName] {
associativity [left/right/none] precedence [preValue]
}
先用上述的語法聲明運算符,然后為自己的類實現運算。
associativity 默認為 none
precedence 默認為 0.