I am investigating MemoryLayout and I came across this:
struct A {
var name:String
}
class B {
var name:String
init(name: String) {
self.name = name
}
}
let a = A(name: "a")
let sizeA = MemoryLayout.size(ofValue: a)
print("struct size: " + "\(sizeA)") // 16
let b = B(name: "B")
let sizeB = MemoryLayout.size(ofValue: b)
print("class size: " + "\(sizeB)"). // 8
Can you please explain to me why the size is different? Thanks
When using
size(ofValue:)for aclass, the returned value is the size of the pointer of that class. However, when dealing with a struct it returns the size of that instance hence the diffrence.More info here: When is my struct too large?