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 MyClas
It's possible if your type parameter implements a common naming protocol.
In the example below the protocol Named ensures that the generic type implements the name class property.
Note that this works with both classes and value types since the latter can also be extended to conform to protocols, as illustrated with the Int below.
protocol Named {
class var name: String { get }
}
class MyClass {
func genericName() -> String {
return T.name
}
}
extension Int: Named {
static var name: String { return "I am an Int" }
}
class Foo: Named {
class var name: String { return "I am a Foo" }
}
enum Drink: Named {
static var name: String { return "I am a Drink" }
}
MyClass().genericName() // I am an Int
MyClass().genericName() // I am a Foo
MyClass().genericName() // I am a Drink