Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does shift left (<<) actually do in Swift?

I'm messing around with a Flappy Bird clone, and i can't figure out what the meaning of the following code is

let birdCategory: UInt32 = 1 << 0
let worldCategory: UInt32 = 1 << 1
let pipeCategory: UInt32 = 1 << 2
let scoreCategory: UInt32 = 1 << 3

Sorry if this is obvious, i've tried looking for the answer but couldn't find it. Thanks

like image 843
Graham Avatar asked May 19 '15 17:05

Graham


People also ask

What does a shift left do?

Shift Left is a practice intended to find and prevent defects early in the software delivery process. The idea is to improve quality by moving tasks to the left as early in the lifecycle as possible. Shift Left testing means testing earlier in the software development process.

What does a left shift by 1 do?

The left-shift of 1 by i is equivalent to 2 raised to power i. As mentioned in point 1, it works only if numbers are positive.

What is the output of left shift operator << on?

Explanation: Left Shift Operator << shifts bits on the left side and fills Zeroes on the Right end.

What does ~= mean in Swift?

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.


1 Answers

That's the bitwise left shift operator

Basically it's doing this

// moves 0 bits to left for 00000001
let birdCategory: UInt32 = 1 << 0 

// moves 1 bits to left for 00000001 then you have 00000010 
let worldCategory: UInt32 = 1 << 1

// moves 2 bits to left for 00000001 then you have 00000100 
let pipeCategory: UInt32 = 1 << 2

// moves 3 bits to left for 00000001 then you have 00001000 
let scoreCategory: UInt32 = 1 << 3

You end up having

birdCategory = 1
worldCategory = 2
pipeCategory = 4
scoreCategory= 8
like image 161
Claudio Redi Avatar answered Sep 17 '22 11:09

Claudio Redi