Thursday, June 4, 2015

MirrorType

Nate Cook:

Reflection in Swift is a limited affair, providing read-only access to a subset of type metadata. While far from the rich array of run-time hackery familiar to seasoned Objective-C developers, Swift’s tools enable the immediate feedback and sense of exploration offered by Xcode Playgrounds.

[…]

The entry point for reflection is the reflect function, which can take an instance of any type as its single parameter and returns a MirrorType. Now, MirrorType is something of an oddity for the Swift standard library: a protocol used as a type. Other than the ubiquitous AnyObject, to date no other protocol is used this way. The particular MirrorType-conforming instance that you receive depends on the type passed to reflect—Swift’s internals define mirrors for types such as Array, Dictionary, Optional, and Range, along with more generic mirrors for structs, classes, tuples, and metatypes.

MirrorType provides the nascent reflection API that Swift offers, wrapping a value along with its type information, information about its children, and different representations of the instance.

[…]

Lastly, we must link WWDCSession to its custom mirror by adding conformance to the Reflectable protocol. Conformance only requires a single new method, getMirror(), which returns a MirrorType—in this case, our shiny new WWDCSessionMirror:

Update (2015-12-20): Benedikt Terhechte:

So, as you can see, using reflection slows the whole process of creating NSManagedObjects down by about 3.5x. This is fine when you’re using this for a limited amount of items, or when you don’t have to care about speed. However, when you need to reflect over a huge amount of structs, this will probably kill your app’s performance.

Comments RSS · Twitter

Leave a Comment