If we follow Swift rule, it is a safe language: there should be no suspicion on the type of an instance, most things are determined when compiling. However, we are used to the flexibility of Objective-C, and there is nothing keeps forever in the programming world. We really need some "dynamic feature" sometime. The most basic and important thing is how can we know the type of instance when the program is running.
It is easy as pie in Objective-C, by using -class
on an object to get its class. We could even use NSStringFromClass
to convert that class and print a string for it:
NSDate *date = [NSDate date];
NSLog(@"%@",NSStringFromClass([date class]));
// Output:
// __NSDate
Unfortunately, there is not a method like class()
on either Swift class or NSObject
subclass in Swift. However, we can use Objective-C runtime to get the class of an instance, since the memory structure is not changed for them:
let date = NSDate()
let name: AnyClass! = object_getClass(date)
print(name)
// Output:
// __NSDate
object_getClass
here is a method defined in Objective-C runtime, which could accept AnyObject!
as an argument and return its type information in the form of AnyClass!
(Yes, it's optional here. We could expect an nil
if we pass a nil
to this method). In Swift, there is a better way to do the same thing, which is dynamicType
. We can easily change the code above to a "Swifter" format, like this:
let date = NSDate()
let name = date.dynamicType
print(name)
// Output:
// __NSDate
Great, it seems we have made with it. But think it over, we are using Objective-C runtime for an NSObject
instance. If we are trying to get the type of a pure Swift object, what will happen? Take built-in String
for example:
let string = "Hello"
let name = string.dynamicType
print(name)
// Output:
// Swift.String
Pretty cool, it works for Swift built-in types as well.
A> Before Swift 1.2, use .dynamicType
on a non-AnyObject built-in type will cause a compiling error. Great news is it got fixed since Swift 1.2. We can use .dynamicType
to get the type of an object in any case.