Get the class name of an object as a string in Swift


This article will explain to you how to get the name of the class of an object in the Swift language.

Swift provides us with a function called type(of:) to get the type of a value or the class name of an object.

You can use the type(of:) function to find the dynamic type of a value, particularly when the dynamic type is different from the static type. The static type of a value is the known, compile-time type of the value. The dynamic type of a value is the value’s actual type at run-time, which can be a subtype of its concrete type.

Example

import Foundation
class Person {
    var name: String?
    var address: String?
}
class Student: Person {
    var rollNumber: Int?
    var schoolName: String?
}
let personObject = Person()
let studentObject = Student()
let className1 = String(describing: type(of: personObject))
let className2 = String(describing: type(of: studentObject))
print("personObject type: \(className1)")
print("studentObject type: \(className2)")

Output

personObject type: Person
studentObject type: Student

Explanation

In the above example, we used the String(describing:) function to get the type in string format.

Conclusion

The type(of:) function is used to get the class name of an object. This function works with any type of object like Int, String, custom objects, etc. You can use the String(describing:) function to convert the object type into string format.

Updated on: 07-Sep-2023

566 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements