Reputation: 1212
UInt8 memory size is 1 byte . but when i make it optional value, it gives 2 byte of size.
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.
how to get exactly 1 byte memory size for Integer value
Upvotes: 3
Views: 408
Reputation: 9391
Under the hood, an optional is an enum and looks something like this:
enum Optional<Wrapped> {
case some(Wrapped) // not nil
case none // nil
}
The symbols ?
and !
are just shorthands for referring to this optional enum. This extra layer causes it to be 2 bytes large.
However, if you unwrap the optional, the returned value is the wrapped value itself, so it becomes 1 byte.
Upvotes: 1