Get "path" of nested types as string in Swift

700 Views Asked by At

The Problem

I'm searching for a generic way to obtain the full name of a nested type in Swift, i.e. when I define nested structs as follows:

struct A {
    struct B {
        struct C {
        }
    }
}

and I create an instance of C, then I want to have a method that returns the full path of that instance's type:

let c = A.B.C()
fullTypeName(c) // should return "A.B.C"

My Approaches

When I use

String(describing: type(of: c))

it only returns the last component C, i.e. the type name relative to the scope in which it's defined.

When I use

String(reflecting: type(of: c))

it actually returns the whole path but with some ugly prefix __lldb_expr_22.A.B.C.

I created a simple custom String initializer from this:

extension String {

    init<Subject>(describingNestedType: Subject) {
        let string = String(reflecting: Subject.self)
        let components = string.split(separator: ".")
        let path = components.dropFirst().joined(separator: ".")
        self = path
    }

}

which works very well:

let c = A.B.C()
let cString = String(describingNestedType: c)
print(cString) // prints "A.B.C"

but using the method String(reflecting:) worries me a little because

  • noone can guarantee that it doesn't return some other prefix in certain cases or no prefix at all
  • the function's description states that it's intended for debugging purposes only.

So is there a way to get the (full) name of a nested type in a safe way?

0

There are 0 best solutions below