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

Jiaaro picture Jiaaro · Jun 7, 2014 · Viewed 223.9k times · Source

When trying to understand a program, or in some corner-cases, it's useful to be able to actually 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 so far I haven't been able to find out the actual type

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

Answer

Jérémy Lapointe picture Jérémy Lapointe · Oct 19, 2016

Swift 3 version:

type(of: yourObject)