Get Class Name In Swift Tutorial

Getting the class name of an object in Swift can be useful for comparing types.

How To Get Class Name In Swift

We can use the type(of: ) function in Swift to determine the class name of an object:

class CustomClass {
    var str: String
}
let customClass = CustomClass()
let className = String(describing: type(of: customClass))
print(className)

This will print out:

CustomClass

You can also use .self like so:

let customClass = CustomClass()
let className = String(describing: customClass.self)
print(className)

However this will print something like this:

__lldb_expr_14.CustomClass

Protocol To Get Class Name

We can also create a protocol that will add on a quick function to get the class name:

protocol ClassName {}
extension ClassName {
    func className() -> String {
        return String(describing: type(of: self))
    }
}

class CustomClass: ClassName {
    var str: String = "test"
}

let customClass = CustomClass()
print(customClass.className())

This will print out:

CustomClass

You can extend any class with the ClassName protocol and then easily access the className by calling className().

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts