-
Notifications
You must be signed in to change notification settings - Fork 135
Get type information in Swift with generics
Mert Buran edited this page Apr 10, 2020
·
1 revision
let metatype = type(of: variable)
func metatypeName<T>(of variable: T) -> String {
let metatype = type(of: variable)
return "\(metatype)"
}
protocol ProtocolThatIHATE {}
struct StructThatILOVE: ProtocolThatIHATE {}
let variable: ProtocolThatIHATE = StructThatILOVE()
metatypeName(of: variable) // returns "ProtocolThatIHATE" ???!!?!
func metatypeName<T>(of variable: T) -> String {
let metatype = type(of: variable as Any) // casting to Any fixes the issue!
return "\(metatype)"
}
metatypeName(of: variable) // returns "StructThatILOVE"! 🙌
- Why does that happen really?