The \"dynamicType.printClassName\" code is from an example in the Swift book. There\'s no way I know of to directly grab a custom class name, but you can check an instances type using the \"is\" keyword as shown below. This example also shows how to implement a custom className function, if you really want the class name as a string.
class Shape {
class func className() -> String {
return \"Shape\"
}
}
class Square: Shape {
override class func className() -> String {
return \"Square\"
}
}
class Circle: Shape {
override class func className() -> String {
return \"Circle\"
}
}
func getShape() -> Shape {
return Square() // hardcoded for example
}
let newShape: Shape = getShape()
newShape is Square // true
newShape is Circle // false
newShape.dynamicType.className() // \"Square\"
newShape.dynamicType.className() == Square.className() // true
Note that subclasses of NSObject already implement their own className function. If you\'re working with Cocoa, you can just use this property.
class MyObj: NSObject {
init() {
super.init()
println(\"My class is \\(self.className)\")
}
}
MyObj()