在Swift中左移(<<)实际上做了什么?

Gra*_*ham 7 xcode bit-shift swift

我正在搞乱Flappy Bird克隆,我无法弄清楚以下代码的含义是什么

let birdCategory: UInt32 = 1 << 0
let worldCategory: UInt32 = 1 << 1
let pipeCategory: UInt32 = 1 << 2
let scoreCategory: UInt32 = 1 << 3
Run Code Online (Sandbox Code Playgroud)

对不起,如果这是显而易见的,我已经尝试寻找答案,但找不到它.谢谢

Cla*_*edi 22

那就是 bitwise left shift operator

基本上它正在这样做

// 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
Run Code Online (Sandbox Code Playgroud)

你最终拥有了

birdCategory = 1
worldCategory = 2
pipeCategory = 4
scoreCategory= 8
Run Code Online (Sandbox Code Playgroud)