Reputation: 396
When I tried to shift bits on my RGB color experiment I've noticed that I couldn't shift a variable number of bits.
The Swift book only states that you move "a number to the left/right"
„The bitwise left shift operator (<<) and bitwise right shift operator (>>) move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.“
Is it intentional only to be able to shift a predefined number of bits?
// Works fine:
let shiftMe: UInt32 = 0xFF0000
let shiftedConst = shiftMe >> 16
// Doesn't work:
let shiftMe: UInt32 = 0xFF0000
let shiftValue:Int = 16
let shiftedConst = shiftMe >> shiftValue
The second example won't compile and throws this error:
Could not find an overload for '>>' that accepts the supplied arguments
Is swift designed like this? Is it a bug and fixed in beta3? (I'm still on beta2 atm.)
Upvotes: 2
Views: 1844
Reputation: 112857
The type of the shift count must match the type of the value being shifted.
shiftValue
must be declared UInt32
.
let shiftMe: UInt32 = 0xFF0000
let shiftValue:UInt32 = 16
let shiftedConst = shiftMe >> shiftValue
IMO it should not make any difference if the shift count type is UInt8, UInt16, uInt32 or uInt64 (or even the signed versions) since the shift range is smaller than any of these types. Further this is an unnecessary stumbling block that is neither documented nor intuitive.
The error message is both unhelpful and incorrect:
error: :39:20: error: 'UInt32' is not convertible to 'UInt8'
let shiftedConst = shiftMe >> shiftValue
Upvotes: 5
Reputation: 24041
those are the overloaded operators in Swift basically† for operator >>
, as you see there is no such operator overloading which works on UInt32
with Int
:
you can overload this operator anytime for your wish, like
func >>(lhs: UInt32, rhs: Int) -> UInt32 {
return lhs >> UInt32(rhs);
}
and your second code snippet will work without any issue in the future:
let shiftMe: UInt32 = 0xFF0000
let shiftValue: Int = 16
let shiftedConst = shiftMe >> shiftValue
you will find more information about custom operators in Swift here.
† in Xcode6 beta, beta2, beta3
Upvotes: 3