HungCLo HungCLo - 1 year ago 101
Swift Question

Swift Array[UInt8] using Bitwise operator not work?

I got confused when testing my code on playground

var test: [UInt8] = [5, 6, 7, 8]

print(test[0]) -> 5

print(5<<8) -> 1280

print(test[0]<<8) -> error

The error turns out to be like above

Can anyone explain it?

Answer Source

When using the bitwise shift operators, you must shift by less than the type size of the value to shift, in bits. In this case, you're trying to shift a UInt8 by 8 bits – which is out of that range.

The reason it's working for print(5<<8) -> 1280 is because Swift is inferring those types to be of Int – and therefore it'll be either 32 or 64 bit, depending on the platform. Because 8 is less than this, it will work.

If you explicitly cast the 5 to UInt8, you'll get a compiler error saying:

Shift amount is greater than or equal to type size in bits

However, it appears Swift is unable to provide the same compiler error for arrays – only a runtime one.

The solution therefore is to work with larger types. Depending on what you're using this code for, you may want to use a UInt16 array.

var test: [UInt16] = [5, 6, 7, 8]

Or you if you're using the shifted values independently of the array, you can just cast them to a larger type before shifting:


Although you should note that Apple recommends you use Int for integer types, even if your values are known to be non-negative – unless you specifically need to work with types of a fixed size.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download