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.self
and SomeClass.Type
, a short example (that doesn't address Type
at all), and that's it.
Meta
In Swift, all types have metatypes, not just classes.
Let's use 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 true
.
Watch out for
AnyObject
. If I had declaredobject
that way then it would hold an Objective-CNSString
cluster instance! This is part of the automatic Objective-C bridging system that also automatically convertstrue
or0.0
intoNSNumber
instances in similar cases.
We can ask if object
is an instance of String
:
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 typeOfObject
is 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 String.Type
metatype:
//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
tl;dr
"beep boop"
is an instance of the structString
- We can get a reference to the
String
struct viaString.self
String.self
is an instance of theString.Type
metatype- The
String.Type
metatype is an instance of theAny.Type
metatype
This blog represents my own personal opinion and is not endorsed by my employer.