Getting the class name of an object in Swift can be useful for comparing types.
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
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()
.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.