// 1. 按位取反运算符
var a: UInt8 = 0b00001111
var b = ~a
print(b,terminator:"\n\n")
// 2. 按位与运算符
var c = a & b
print(c,terminator:"\n\n")
// 3. 按位或运算符
var d = a | b
print(d,terminator:"\n\n")
// 4. 按位异或运算符
var e = a ^ b
print(e, terminator:"\n\n")
// 5. 位移运算符
let pink: UInt32 = 0xCC6699
let redComponet = (pink & 0xFF0000) >> 16
let greenComponent = (pink & 0x00FF00) >> 8
let blueComponent = pink & 0x0000FF
print("red:\(redComponet) green:\(greenComponent) bule:\(blueComponent)")
溢出云算符 &+, &-, &*
// 1. 下溢(从最小值变为最大值)
var a = UInt8.min
a = a &- 1
print(a)
// 2. 上溢 (从最大值变为最小值)
var b = Int8.max
b = b &+ 1
print(b)
运算符函数
struct Vector2D {
var x = 0.0, y = 0.0
}
extension Vector2D: Equatable{
// 1. 中缀运算符函数
static func + (left: Vector2D, right: Vector2D) -> Vector2D{
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// 2. 前缀和后缀运算符函数
static prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
// 3. 符合运算符函数
static func += (left: inout Vector2D, right: Vector2D) {
return left = left + right
}
// 4. 等价运算符函数
static func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
}
var a = Vector2D(x: 3, y: 5)
var b = Vector2D(x: 4, y: 6)
var c = a + b
print("c.x = \(c.x) c.y = \(c.y)")
var d = -c
print("d.x = \(d.x) d.y = \(d.y)")
d += c
print("d.x = \(d.x) d.y = \(d.y)")
if c == d {
print("c == d")
}else{
print("c != d")
}