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 :)
If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use
is
, oras?
as in the following:This is equivalent of
isKindOfClass
in Obj-C.And this is equivalent of
conformsToProtocol
, orisMemberOfClass
Swift 3 version:
Here is 2 ways I recommend doing it:
Or:
Here is a detailed example:
If you get an "always true/fails" warning you may need to cast to Any before using
is
This works in swift 3