What is Swift enum byte representation? -
i have following enum:
enum enum: uint8 { case = 0x00 case b = 0x01 case c = 0x10 }
i use following code convert nsdata
:
var value = enum.c let data = nsdata(bytes: &value, length: 1)
naturally, expect data
contain 0x10
, however, contains 0x02
.
for enum.a
contains 0x00
, enum.b
contains 0x01
.
to me, looks stores index of value instead of actual raw data. explain behavior?
p.s. if use rawvalue
works perfectly. however, want understand reason behind, since because of cannot create generic function convert values nsdata.
the swift abi still work in progress (expected fixed swift 4). way enums represented in memory is described here.
your case "c-like enum" because has...
- two or more cases
- no associated values
quoting abi document:
the enum laid out integer tag minimal number of bits contain of cases. [...] cases assigned tag values in declaration order.
the crucial information here "minimal number of bits". means (for case) instances should fit 2 bits (as have 3 cases). rawvalue 0x10
need 5 bits—which in conflict abi.
the compiler uses static tables convert between instances of enum
, rawvalue
(and back).
here's example highlights characteristic of abi:
enum enum: uint32 { case = 0 case b = 0xffffffff // value not fit 1 byte } assert(sizeof(enum.self) == 1)
Comments
Post a Comment