Saturday, March 14, 2015

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 of objectType can be used to create a new SomeClass instance just like how a Class value would be used in Objective-C.

[…]

If you examine Swift in Xcode you may have noticed the Reflectable and MirrorType 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 to Reflectable and despite the lack of a getMirror() implementation we are still able to produce a mirror when calling reflect(brew). This works because the runtime provides a fall back MirrorType implementation that works for any type when a mirror is not directly provided for a type.

Comments RSS · Twitter

Leave a Comment