I\'m aware you can use MemoryLayout to get the size of a type T.
For example: MemoryLayout
As far as I tested in the Playground, this function returns seemingly significant value:
func heapSize(_ obj: AnyObject) -> Int {
return malloc_size(Unmanaged.passRetained(obj).toOpaque())
}
class MyClass {
//no properites...
}
let myObj = MyClass()
print(heapSize(myObj)) //->16
class MyBiggerClass {
var str: String?
var i: Int = 0
}
let myBiggerObj = MyBiggerClass()
print(heapSize(myBiggerObj)) //->64
Seems the current Swift runtime uses malloc-compatible something to allocate memory in heap. (malloc gives some padding to fit the allocated size to power to 2, when allocating small chunks. So, the actually needed size for the instance may be smaller than the malloc_size.)
I haven't tested how far this would work, and undocumented behaviours just depending on the current implementation would change at any time in the future without any notifications.
But if you actually know that, this can be a good starting point for exploration.