10

I cannot seem to find a function or method that returns the type of an object in Swift.

How does one retrieve the type or class of an object in Swift?

I tried using Obj-C classes which obviously did not work.

In python you have things like type or isinstance

In Javascript you have constructor

Johnston
  • 20,196
  • 18
  • 72
  • 121

2 Answers2

11

If you just need to check an object's type, you can use the type check operator, is, as in:

if myObject is UIView {
    // do something
}

If you want to try to call a method on the object but you aren't sure of the class, downcast the object to the type you need, like this:

if let myView = myObject as? UIView {
    myView.layer.backgroundColor = myColor
}
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
-1

Are you looking for dynamicType?

someInstance.dynamicType.printClassName()
Analog File
  • 5,280
  • 20
  • 23