Getting enclosing type name

In this fragment I can get "enclosing" type name (in this case it is "Foo" for Bar) by "po" or "p" in the debugger, is it possible to get it from the app?

// looking for "Foo"
struct Foo {
    struct Bar {
        func foo() {
            print(self)           // ❌ Bar()
            print(Self.self)      // ❌ Bar
            print(type(of: self)) // ❌ Bar  
            // po self            // ✅ JT.Foo.Bar()
            // p self             // ✅ (JT.Foo.Bar) 
        }
    }
}

The easiest way I know of is to pass the metatype to String.init(reflecting:). In your case:

print(String(reflecting: type(of: self)))

In an Xcode playground, this prints something like __lldb_expr_70.Foo.Bar. In a command line program, it prints main.Foo.Bar for me.

I don't think this behavior is documented, so technically the format could change, though I doubt it will.

Another option is to use a reflection library such as Echo, which provides access to most (or all?) of the type metadata that's stored in the binary, including parent types and their names.

2 Likes