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 :)
Depends on the use case. But let's assume you want to do something useful with your "variable" types. The Swift
switch
statement is very powerful and can help you get the results you're looking for...In this case, have a simple dictionary that contains key/value pairs that can be UInt, Int or String. In the
.filter()
method on the dictionary, I need to make sure I test for the values correctly and only test for a String when it's a string, etc. The switch statement makes this simple and safe! By assigning 9 to the variable of type Any, it makes the switch for Int execute. Try changing it to:..and try it again. This time it executes the
as String
case.In Swift 2.0 the proper way to do this kind of type introspection would be with the Mirror struct,
Then to access the type itself from the
Mirror
struct you would use the propertysubjectType
like so:You can then use something like this:
For Swift 3.0
For Swift 2.0 - 2.3
As of Xcode 6.0.1 (at least, not sure when they added it), your original example now works:
Update:
To answer the original question, you can actually use the Obj-C runtime with plain Swift objects successfully.
Try the following:
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.
Note that subclasses of NSObject already implement their own className function. If you're working with Cocoa, you can just use this property.