UInt8 内存大小为 1 字节。 但是当我将其设置为可选值时,它给出了 2 个字节的大小。
var serail : UInt8? = 255
print(MemoryLayout.size(ofValue: serail)) // it gives 2 byte size.
var serail : UInt8 = 255
print(MemoryLayout.size(ofValue: serail)) // it gives 1 byte size.
如何为整数值获取正好 1 字节的内存大小
在引擎盖下,可选的是一个枚举,看起来像这样:
enum Optional<Wrapped> {
case some(Wrapped) // not nil
case none // nil
}
符号 ?
和 !
只是引用此可选枚举的简写。这个额外的层导致它有 2 个字节大。
但是,如果解开 optional,则返回的值是包装的值本身,因此它变为 1 个字节。