Swift: 2 ways to get the type of a variable at runtime

Updated: April 18, 2023 By: Khue Post a comment

This succinct, practical article will walk you through a couple of different approaches to determining the data type of a variable at runtime in Swift. Without any further ado, let’s get started.

Using the type(of:) function

The type(of:) function is the easiest and most convenient way to get the data type of a Swift variable. Below is the syntax:

var typeOfMyVariable = type(of: yourVariable)

Example:

var a = 123
var b = "Sling Academy"
var c = false

print("Type of a is \(type(of: a))")
print("Type of b is \(type(of: b))")
print("Type of c is \(type(of: c))")

Output:

Type of a is Int
Type of b is String
Type of c is Bool

Note: In the new versions of Swift, the dynamicType property is no longer available. In the past (Swift 2 or earlier), dynamicType was a property of any value.

Using the “is” or “as” operators

You can use the is operator with the if/else or switch/case statement to check the type of a variable.

Example (with custom types):

// Define some types
class Animal {}
class Dog: Animal {}
class Cat: Animal {}

// Create a variable of type Animal
var pet: Animal = Dog()

// Use switch/case and is to check the type of pet
switch pet {
case is Dog:
    print("It's a dog")
case is Cat:
    print("It's a cat")
default:
    print("It's some other animal")
}

The as operator can be used to check whether a variable is castable to another type or not.

Example:

// Create a variable of type Any
var value: Any = 42

// Use as? to check if value can be casted to Int
if let _ = value as? Int {
    print("It's an integer")
} else {
    print("It's not an integer")
}

Output:

It's an integer