Enumerations in Swift have associated values. Different enumerators can have different types of associated values.

enum TestEnum {
    case test0(a:Int,b:Int,c:Int)
    case test1(a:Int,b:Int)
    case test2(a:Bool)
    case test3}Copy the code

The enumeration in the above example has four members, the first three of which are associated with different types and numbers of associated values. You can view the actual memory usage and memory allocation of the TestEnum type in the following ways

print("Memory usage of type TestEnum: + "\(MemoryLayout<TestEnum>.size)") /// Memory usage of the TestEnum type :25print("Memory allocation of type TestEnum: + "\(MemoryLayout<TestEnum>.stride)") /// Memory allocation of type TestEnum :32print("Memory alignment of type TestEnum: + "\(MemoryLayout<TestEnum>.alignment)") /// Memory alignment of type TestEnum :8Copy the code

Look at the memory footprint and allocation of a single variable of type TestEnum

t0

0A 00 00 00 00 00 00 00 00 //10 0B 00 00 00 00 00 00 00 00 //11 0C 00 00 00 00 00 00 00 00 00 00 //12 00 00 00 00 00 00 00 00 00 00 // Member value store 0Copy the code

Note: Apple’s address is in small-endian mode. We see 0A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64. Int is the same size as Int64.

The first 24 bytes can be seen as memory for three associated values, and the use of the 25th byte can be checked by looking at the memory layout of the other member values.

Summary: The memory footprint of an enumeration type variable can be interpreted as 1 byte of stored member value (indicating which member it is) plus the number of bytes of the associated value that occupies the largest number of bytes. For example, the above is (24 + 1), and due to the principle of memory alignment, the actual allocation is 32 bytes.

If there is no associated value, then memory only needs one byte to store which member it is. As follows: