hpique hpique - 1 year ago 135
Swift Question

Bitwise operations with CGBitmapInfo and CGImageAlphaInfo

I'm having trouble performing bitwise operations with

in Swift.

In particular, I don't know how to port this Objective-C code:

bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;

The following straightforward Swift port produces the somewhat cryptic compiler error
'CGBitmapInfo' is not identical to 'Bool'
on the last line:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst

Looking at the source code I noticed that
is declared as a
isn't. Maybe this has something to do with it?

It doesn't help that the official documentation on bitwise operators doesn't cover enums.

Answer Source

You have the right equivalent Swift code:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)

It's a little strange because CGImageAlphaInfo isn't actually a bitmask -- it's just a UInt32 enum (or a CF_ENUM/NS_ENUM with type uint32_t, in C parlance), with values for 0 through 7.

What's actually happening is that your first line clears the first five bits of bitmapInfo, which is a bitmask (aka RawOptionSetType in Swift), since CGBitmapInfo.AlphaInfoMask is 31, or 0b11111. Then your second line sticks the raw value of the CGImageAlphaInfo enum into those cleared bits.

I haven't seen enums and bitmasks combined like this anywhere else, if that explains why there isn't really documentation. Since CGImageAlphaInfo is an enum, its values are mutually exclusive. This wouldn't make any sense:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download