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:
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
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.