Error in memory calculations


#1

After the following example
i​n​d​i​r​e​c​t​ ​e​n​u​m​ ​F​a​m​i​l​y​T​r​e​e​ ​{​
​ ​ ​ ​c​a​s​e​ ​N​o​K​n​o​w​n​P​a​r​e​n​t​s​
​ ​ ​ ​c​a​s​e​ ​O​n​e​K​n​o​w​n​P​a​r​e​n​t​(​n​a​m​e​:​ ​S​t​r​i​n​g​,​ ​a​n​c​e​s​t​o​r​s​:​ ​F​a​m​i​l​y​T​r​e​e​)​
​ ​ ​ ​c​a​s​e​ ​T​w​o​K​n​o​w​n​P​a​r​e​n​t​s​(​f​a​t​h​e​r​N​a​m​e​:​ ​S​t​r​i​n​g​,​ ​f​a​t​h​e​r​A​n​c​e​s​t​o​r​s​:​ ​F​a​m​i​l​y​T​r​e​e​,​
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​m​o​t​h​e​r​N​a​m​e​:​ ​S​t​r​i​n​g​,​ ​m​o​t​h​e​r​A​n​c​e​s​t​o​r​s​:​ ​F​a​m​i​l​y​T​r​e​e​)​
}​

You said that “The size of an instance of FamilyTree is now 8 bytes on a 64-bit architecture – the size of one pointer.”. But I think this is not true because there is one byte to keep track of which case the instance actually is, plus the memory assigned to “fatherName”, the memory assigned to “m​o​t​h​e​r​N​a​m​e​”, 8 bytes the size of one pointer to “​f​a​t​h​e​r​A​n​c​e​s​t​o​r​s​” and 8 bytes the size of one pointer to “​m​o​t​h​e​r​A​n​c​e​s​t​o​r​s​”. so the size of an instance of FamilyTree is more than 17 bytes.


#2

The surface structure of Swift looks simple, but its deep structure does not look so simple.

To see this, experiment with the MemoryLayout construct.

struct S {
    let A = 1
    let B = 2
    let C = 4
    let D = 8
}
//
class C {
    let A = 1
    let B = 2
    let C = 4
    let D = 8
}
//
indirect enum Color {
    case noColor
    case red   (UInt)
    case green (UInt)
    case blue  (UInt)
    case mixed (R:Color, G:Color, B:Color)
}
//
print ("struct...")
print (MemoryLayout<S>.size)
let s = S ()
print (MemoryLayout.size (ofValue:s))
print ();
//
print ("class...")
print (MemoryLayout<C>.size)
let c = C ()
print (MemoryLayout.size (ofValue:c))
print ();
//
print ("enum...")
print (MemoryLayout<Color>.size)
let n = Color.noColor
print (MemoryLayout.size (ofValue:n))
let r = Color.red (1)
print (MemoryLayout.size (ofValue:r))
let m = Color.mixed (R: Color.red (1), G: Color.green (0), B: Color.blue (1))
print (MemoryLayout.size (ofValue:m))

Output:

struct...
32
32

class...
8
8

enum...
8
8
8
8