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
selfexpression. […] Now the value ofobjectTypecan be used to create a newSomeClassinstance just like how aClassvalue would be used in Objective-C.[…]
If you examine Swift in Xcode you may have noticed the
ReflectableandMirrorTypeprotocols. […] 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
reflectmethod 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
Brewstruct does not conform toReflectableand 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 backMirrorTypeimplementation that works for any type when a mirror is not directly provided for a type.