Get Class Name In Swift Tutorial

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts