Type & Self
Way too meta
In Objective-C, every class is an instance of its metaclass.
What about Swift? If you've looked closely at the Swift Language Reference you'll see two short paragraphs describing
SomeClass.Type, a short example (that doesn't address
Type at all), and that's it.
In Swift, all types have metatypes, not just classes.
let object:Any = "beep boop". I'm using
Any here to force the compiler to forget what it knows about the type, otherwise it is too smart and flags the test below as always returning
Watch out for
AnyObject. If I had declared
objectthat way then it would hold an Objective-C
NSStringcluster instance! This is part of the automatic Objective-C bridging system that also automatically converts
NSNumberinstances in similar cases.
We can ask if
object is an instance of
let isString = object is String //true
We can use reflection to figure out the type of
object (and cast to
Any.Type here to again defeat the smartypants compiler).
let mirror = Mirror(reflecting: object) let typeOfObject:Any.Type = mirror.subjectType
Now how can we ask whether
String? You might try this code:
let isStringType = typeOfObject is String //warning:Cast from 'Any.Type' to unrelated type 'String' always fails
It doesn't work because we are operating abstractly.
typeOfObject is not an instance of
String, it's an instance of the
String.Type metatype. (I like to think of
String.self as being the
String struct.) Now we've found a use for the
//Swift 1.2 let isStringType = typeOfObject is String.Type
As of Swift 2 you can also directly compare metatypes for equality:
let isStringType = typeOfObject == String.self
"beep boop"is an instance of the struct
- We can get a reference to the
String.selfis an instance of the
String.Typemetatype is an instance of the
This blog represents my own personal opinion and is not endorsed by my employer.