How do you find out the type of an object (in Swift)?

Answer

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()

 

All swift Questions

Ask your interview questions on swift

Write Your comment or Questions if you want the answers on swift from swift Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---