danilabagroff
danilabagroff

Reputation: 656

Bitwise and arithmetic operations in swift

Honestly speaking, porting to swift3(from obj-c) is going hard. The easiest but the swiftiest question.

public func readByte() -> UInt8
{
    // ...
}

public func readShortInteger() -> Int16
{
    return (self.readByte() << 8) + self.readByte();
}

Getting error message from compiler: "Binary operator + cannot be applied to two UInt8 operands."

What is wrong?

ps. What a shame ;)

Upvotes: 1

Views: 913

Answers (2)

rustyMagnet
rustyMagnet

Reputation: 4085

Apple has some great Swift documentation on this, here:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html

let shiftBits: UInt8 = 4   // 00000100 in binary
shiftBits << 1             // 00001000
shiftBits << 2             // 00010000
shiftBits << 5             // 10000000
shiftBits << 6             // 00000000
shiftBits >> 2             // 00000001

Upvotes: 0

Margaret Bloom
Margaret Bloom

Reputation: 44046

readByte returns a UInt8 so:

  1. You cannot shift a UInt8 left by 8 bits, you'll lose all its bits.
  2. The type of the expression is UInt8 which cannot fit the Int16 value it is computing.
  3. The type of the expression is UInt8 which is not the annotated return type Int16.

d

func readShortInteger() -> Int16
{
    let highByte = self.readByte()
    let lowByte = self.readByte()

    return Int16(highByte) << 8 | Int16(lowByte)
}

While Swift have a strictly left-right evaluation order of the operands, I refactored the code to make it explicit which byte is read first and which is read second.

Also an OR operator is more self-documenting and semantic.

Upvotes: 4

Related Questions