Gregory Higley
Gregory Higley

Reputation: 16558

How can I get the fully qualified name of the runtime type of a generic parameter in Swift?

E.g.,

func inject<P, D>(params: P, create: P -> D) {
    let type = String(D)
    // etc.
}

The technique above seems to work for any Swift type (including protocols), but unfortunately type does not contain the module name, just the type itself. In other words, if D is Watusi and Watusi is in the Zing module, I want Zing.Watusi, not just Watusi.

Anyone know how to get the whole enchilada, for any Swift type passed as a generic parameter?

Ultimately, the purpose of this is to use the fully qualified type as a key in this dependency resolver implementation.

Note: Anton Bronnikov made an excellent suggestion below. It's one I was aware of, but I should clarify that I need a public API for this, otherwise the app will be rejected and my client will be unhappy.

Upvotes: 1

Views: 245

Answers (2)

Gregory Higley
Gregory Higley

Reputation: 16558

The answer is String(reflecting: D.self), where D is a type.

Upvotes: 0

0x416e746f6e
0x416e746f6e

Reputation: 10136

I think you can get closer to what you want with:

func inject<P, D>(params: P, create: P -> D) {
    let type = _stdlib_getDemangledTypeName(D)
    // etc.
}

Above will produce almost the string you want except with "unnecessary" .Type in the end.

Upvotes: 1

Related Questions