Get type information in Swift with generics - DataDog/dd-sdk-ios GitHub Wiki

Origin of this entry: PR #74

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