2015-05-19 90 views
3

我瞎搞了笨鳥先飛的克隆,我不能找出以下代碼的含義是左移(<<)實際上在Swift中做了什麼?

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

很抱歉,如果這是顯而易見的,我已經嘗試過尋找答案,但找不到它。謝謝

+1

這不是Objective-C的,但迅速 –

+0

woops,感謝指出了這一點,現在改。 – Graham

+1

官方Swift文檔中的<< <<'在[Advanced Operators](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html)中有很好的描述(帶插圖) 。 –

回答

13

這就是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 

最終不得不

birdCategory = 1 
worldCategory = 2 
pipeCategory = 4 
scoreCategory= 8 
2

首先,你發佈了Swift代碼,而不是Objective-C。

但是我想這是一個* 2^x的一個字節移位,就像在普通的舊C.

a << x等同。通過將這些位向左移動一個位置,可以使您的值翻倍。這樣做x次會產生2^x倍的值,當然,除非溢出。

您可以閱讀有關如何在計算機here中表示數字的方法。