Advanced Operators

  • 高级运算符。不同于C,swfit中的运算符默认是不可溢出的,溢出会报错。你可以使用&加运算符表示可溢出运算符。
  • 按位取反运算符
    let initialBits: UInt8 = 0b00001111
    let invertedBits = ~initialBits  // equals 11110000
    
  • 按位与运算符
    let firstSixBits: UInt8 = 0b11111100
    let lastSixBits: UInt8  = 0b00111111
    let middleFourBits = firstSixBits & lastSixBits  // equals 00111100
    
  • 按位或运算符
    let someBits: UInt8 = 0b10110010
    let moreBits: UInt8 = 0b01011110
    let combinedbits = someBits | moreBits  // equals 11111110
    
  • 按位异或运算符:不同为1 相同为0
    let firstBits: UInt8 = 0b00010100
    let otherBits: UInt8 = 0b00000101
    let outputBits = firstBits ^ otherBits  // equals 00010001
    
  • 按位左移/右移运算符。按位左移实际为乘以2,右移为除以2。位运算时超出舍弃,空位用0填补。
    let shiftBits: UInt8 = 4   // 00000100 in binary
    shiftBits << 1             // 00001000
    shiftBits << 2             // 00010000
    shiftBits << 5             // 10000000
    shiftBits << 6             // 00000000
    shiftBits >> 2             // 00000001
    
  • Int16最大为255,当超过这个值时就会溢出报错。当使用&加基本运算符(+-*)可以人为允许溢出。此时为按位运算然后舍弃超出部分。例如11111111&+00000001=100000000,舍弃第九位为00000000,所以最终为0。-128&-1=127,255&+1=0。
  • swfit中可以自定义重载基本运算符。如重载+实现结构体相加。

你可能感兴趣的:(Advanced Operators)