Get the name (string) of a generic type in Swift

Rob picture Rob · Aug 25, 2014 · Viewed 15.6k times · Source

I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example.

class MyClass<T> {
    func genericName() -> String {
        // Return the name of T.
    }
}

I have been looking around for hours and I can't seem to find any way to do this. Has anyone tried this yet?

Any help is greatly appreciated.

Thanks

Answer

Bradley Hilton picture Bradley Hilton · Apr 26, 2015

You can return any types' name by using string interpolation:

class MyClass<T> {
    func genericName() -> String {
        return "\(T.self)"
    }
}

You can try it in a playground and it works as expected:

var someClass = MyClass<String>()
someClass.genericName() // Returns "Swift.String"