Print type of variable

We can print the type of a value/object:

class A {}
class B: A {}

func getA() -> A {
    return B()
}

let a = getA()
print(type(of: a)) // B

I was wondering whether it is possible to print the type of the variable. So, instead of printing 'B', it would print 'A', the type that has been inferred for 'a'.

If all that you want is to know the inferred type of a variable, and that you use Xcode, and that you feel lucky, alt-click the variable name. Xcode will display its inferred type:

Unfortunately, Xcode will not always perform this task correctly. Sometimes it will fail displaying the desired information.

Not sure what your use case for this is, but you could always use a generic function – the placeholder of which is satisfied by the static type of the argument passed, for example:

class A {}
class B : A {}

func getA() -> A {
  return B()
}

func printStaticType<T>(of _: T) {
  print(T.self)
}

let a = getA()
printStaticType(of: a) // A
2 Likes

I just ran into this when I copied some code into an online compiler and I wondered what type was inferred.

Nice solution, I didn't think of that.

I guess there is no standard way to do this. Would it be worthwhile to add this to the standard library?

I guess it would be something like this then:

func staticType<T>(of _: T) -> String {
    return String(describing: T.self)
}

It should return a type instead of a String, just like type(of:)

Ah, I always thought type(of:) just returned a String! Second attempt:

func staticType<T>(of _: T) -> T.Type {
    return T.self
}
1 Like

Not sure what others think (you could always float it on evolution/pitches), but personally I think this is better done through tooling than the standard library. I don't know how straightforward it is currently, but I believe such online playgrounds should be able to use SourceKit in order to request doc info and use that in order to show the inferred types of declarations.

1 Like

I created a pitch: