[英]Swift - static let and “<<” meaning
我有以下代碼
struct Physics {
static let smallCoin : UInt32 = 0x1 << 1
static let smallCoin2 : UInt32 = 0x1 << 2
static let ground : UInt32 = 0x1 << 3
}
我想知道什么意思
static let
UInt32 = 0x1 << 3
<<
是左移運算符。 您可以更好地將其可視化為二進制:
1 0000 0001
<< 1 ^ shift this one bit to the left
---- = ---------
2 0000 0010
1 0000 0001
<< 2 ^ shift this two bits to the left
---- = ---------
4 0000 0100
3 0000 0011
<< 2 ^ shift this two bits to the left
---- = ---------
12 0000 1100
要記住的另一個屬性是x << n = x * (2^n)
。 <<
的反面是>>
- 右移運算符。
看起來這個問題可能來自需要為物理模擬提供一些常量。 整數可能代表吸引力(或類似的)或世界中的一組項目。 這會很好。
這讓我們進入問題的第一部分:
靜態讓這里為什么你可以使用AA幾個原因static let
房產:
我們將專注於其中的第一個。
現在的問題是關於stuct
這種struct
可以很好地代表類似的常量。 我在許多項目中都有這個,盡管我通常使用 enum 而不是建議的struct
,格式如下
struct Constants {
static let offset = 10
}
enum {
static let offset = 10
}
對於 struct 和 enum 之間的區別,請看這篇文章
這就引出了一個問題,我們有一個 smallCoin 的值,smallCoin2 和 ground 表示為struct
的static let
。
UInt32 = 0x1 << 3給定的類型(我假設這是一個常量)。 這里給出的類型是UInt32這意味着該值是一個無符號的Integer ,然后這個值被指定為0x1 << 1
、 0x1 << 2
或0x1 << 3
取決於我們所指的屬性。
要理解這一點,我們需要認識到0x1
是十六進制,並代表 1 的否認值。 從那里,我們使用https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html :
初始值 1,位移 1 創建值 2。初始值 1,位移 2 創建值 4。初始值 1,位移 3 創建值 8。
現在為什么我們需要像這樣對單個值進行位移位並不完全清楚。
結果,Physics.smallCoin = 2,Physics.smallCoin2 = 4 和 Physics.ground = 8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.