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
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"