如标题所述,lldb 将 UInt.max
的值报告为 -1
的 UInt
,这似乎非常不合逻辑。考虑到 let uint: UInt = -1
甚至都无法编译,这怎么可能呢?我看不出有任何方法可以在运行时使 UInt 为负值,因为如果给定负值,初始化程序将崩溃。我想知道 UInt 的实际最大值。
最佳答案
-1
的Int
值和UInt.max
的UInt
值在内存。
如果你这样做,你可以看到:
let i = Int(bitPattern: UInt.max) // i == -1
反方向:
if UInt(bitPattern: Int(-1)) == UInt.max {
print("same")
}
输出:
same
调试器错误地将 UInt.max
显示为带符号的 Int
。它们在内存中具有相同的位表示(在 iPhone 6 等 64 位系统上为 0xffffffffffffffff
,在 iPhone 5 等 32 位系统上为 0xffffffff
),并且调试器显然选择将该值显示为 Int
。
如果这样做,您会看到同样的问题:
print(String(format: "%d", UInt.max)) // prints "-1"
这并不意味着 UInt.max
是 -1
,只是两者在内存中具有相同的表示。
要查看 UInt
的最大值,请在应用程序或 Swift Playground 中执行以下操作:
print(UInt.max)
这将在 64 位系统(如 Macintosh 或 iPhone 6)上打印 18446744073709551615
,在 32 位系统(如 iPhone 5)上打印 4294967295
).
在 lldb 中:
(lldb) p String(UInt.max)
(String) $R0 = "18446744073709551615"
(lldb)
关于Swift:为什么 UInt.max == -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369708/