高级运算符

  1. 位运算符
// 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. 溢出云算符
    &+, &-, &*
// 1. 下溢(从最小值变为最大值)
var a = UInt8.min
a = a &- 1
print(a)

// 2. 上溢 (从最大值变为最小值)
var b = Int8.max
b = b &+ 1
print(b)
  1. 运算符函数
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")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值