Simple Reflection in Swift
Angelo Di Paolo (via Aaron Brager):
Swift offers metatype type to refer to the type of any Swift type such as enumerations, structures, and protocols. To access the value of the metatype type use the postfix
self
expression. […] Now the value ofobjectType
can be used to create a newSomeClass
instance just like how aClass
value would be used in Objective-C.[…]
If you examine Swift in Xcode you may have noticed the
Reflectable
andMirrorType
protocols. […] This mirror-based reflection API is not yet officially documented anywhere (at least that I know of) and it seems that for now it is mostly used by the REPL. However, this limited API does give us the capability to inspect some basic information about our values.[…]
The Swift standard library defines a
reflect
method that takes a value of any type and returns a mirror (MirrorType
) object which provides information about the value such as its type and properties.[…]
You may have noticed that our
Brew
struct does not conform toReflectable
and despite the lack of agetMirror()
implementation we are still able to produce a mirror when callingreflect(brew)
. This works because the runtime provides a fall backMirrorType
implementation that works for any type when a mirror is not directly provided for a type.