Skip to content

Get type information in Swift with generics

Mert Buran edited this page Apr 10, 2020 · 1 revision

"Well, that's easy..."

let metatype = type(of: variable)

"Generics? Why would it be different?"

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

"Whot? Is StructThatILOVE ghosting me? 😱"

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

...and they lived happily ever after.


Open questions

  1. Why does that happen really?