How Swift implement type(of:)?

179 Views Asked by At

As we all know, Objective-C class owns an isa pointer, so we can get class metadata by this pointer, and Swift value type DO NOT have an isa, but type(of: aInstance) still return its metatype, how does it works?

struct Foo {
    var bar: Int
}

var foo: Any = Foo(bar: 10)
print(type(of: foo))
let ptr = withUnsafeMutablePointer(to: &foo) {
    UnsafeMutableRawPointer($0)
}
print(ptr)
print(ptr.assumingMemoryBound(to: Int.self).pointee)

// Foo
// 0x00000001000081d8
// 10

The memory address owns the value 10, and how can Swift infer its dynamic type by type(of:) at runtime?

0

There are 0 best solutions below