位操作符
非:~
与:&
或:|
异或:^
左移:<<
右移:>>
对于无符号表示和有符号表示,位移行为不一样。
溢出运算符
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.