Ios – How to find out the type of an object (in Swift)

iosswifttypechecking

When trying to understand a program, or in some corner-cases, it's useful to find out what type something is. I know the debugger can show you some type information, and you can usually rely on type inference to get away with not specifying the type in those situations, but still, I'd really like to have something like Python's type()

dynamicType (see this question)

Update: this has been changed in a recent version of Swift, obj.dynamicType now gives you a reference to the type and not the instance of the dynamic type.

This one seems the most promising, but I haven't been able to find out the actual type so far.

class MyClass {
    var count = 0
}

let mc = MyClass()

# update: this now evaluates as true
mc.dynamicType === MyClass.self

I also tried using a class reference to instantiate a new object, which does work, but oddly gave me an error saying I must add a required initializer:

works:

class MyClass {
    var count = 0
    required init() {
    }
}

let myClass2 = MyClass.self
let mc2 = MyClass2()

Still only a small step toward actually discovering the type of any given object though

edit: I've removed a substantial number of now irrelevant details – look at the edit history if you're interested 🙂

Best Answer

Swift 3 version:

type(of: yourObject)