Get Object Type
Posted by Wang Wei (@ONEVCAT) on 2015/05/27
We have repeatedly stressed that Swift is a fairly safe language if you follow the rules: There is no type of doubt, and the vast majority of content should be uniquely identified during compilation. But no matter how many developers in the objective-c have been accustomed to the flexibility, or in the program world is always the ever-changing needs, it is impossible to guarantee a dust unchanged. Sometimes we also need to introduce some dynamic characteristics. One of the most basic, but most useful, techniques is to get any instance type.
In Objective-c we can do this easily, using -class methods to get the class of the object, and we can even NSStringFromClass convert it to a printable string:
NSDate *date = [NSDate date];NSLog(@"%@",NSStringFromClass([date class]));// 输出:// __NSDate
In Swift, we will find that no matter the class or subclass of pure Swift NSObject , there is no class() way to get a type like the original. For NSObject subclasses, because there is no big change in how the information is stored in the class, we can resort to the runtime of Objective-c to get the class and transform it in the same way:
let date = NSDate()let name: AnyClass! = object_getClass(date)println(name)// 输出:// __NSDate
It object_getClass is a method defined in the runtime of Objectivec, which can accept arbitrary AnyObject! and return its type AnyClass! (note the exclamation point here, which indicates that we can even enter nil and expect it to return a nil). In Swift, in fact, in order to get the NSObject actual type of the object or its subclasses, there is actually a good-looking notation for this call, that is dynamicType . The code above is converted in a "more Swift" language, and it will look like this:
let date = NSDate()let name = date.dynamicTypeprintln(name)// 输出:// __NSDate
Well, it seems that our problem can be solved. But think about it, what happens when we use the dynamic characteristics of objective-c, and if we replace it with a Swift built-in type? Like the native String ,
let string = "Hello"let name = string.dynamicTypeprintln(name)// 输出:// Swift.String
It is also possible to see the native types of Swift.
Prior to Swift 1.2, the use of '. DynamicType ' directly on a non-anyobject type built into swift may result in a compilation error or fail to get the correct result. But as Swift continues to refine and improve, we can now use '. DynamicType ' to get the type of an object in a unified manner.
Get Object Type