[英]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.