#45: Get the Type of a Variable in Swift

When you want to inspect the runtime type of a value, use type(of:):

let value: Any = 42
print(type(of: value))
// Int

This is especially useful in debugging code and generic utilities.

If you are doing type-specific logic, prefer casting with as? or pattern matching instead of comparing string representations of types.


I'm also on Twitter and GitHub.

Subscribe via RSS.