Reflection in Swift
Or are we talking introspection?
--
It is often claimed that reflection is not really used in Swift as it is a statically typed language, but actually it gives us read-only access to an object’s properties (importantly) at runtime.
If you have a class you can use reflection to iterate through all of the values
Difficulty: Easy | Normal | Challenging
Prerequisites:
- Be able to (at least) create a “Hello, World!” App in Playgrounds (guide HERE)
- Swift data types, some understanding of OO concepts.
Terminology
Any: An instance of any type, including function types
Introspection: A way to look at an object’s properties without modifying them. Swift reflection should rather be called introspection.
Mirror: A description of the parts that make up a particular instance. For Swift, access to these objects is read-only.
Reflection: An API used to examine or modify the behaviour of methods, classes and interfaces at runtime.
Uses of mirror in Swift
Inspect type data of structs or classes
Basically we can query data in our code. That means we can read through the list of properties that are available at runtime. Here we
enum Species {
case dog
case cat
}struct Animal {
var name: String
var species: Species
}var taylor = Animal(name: "Derek", species: .dog)
var mirror = Mirror(reflecting: taylor)print (mirror) // "Mirror for Animal"
The printing here that prints to the console “Mirror for Animal” is not too interesting. The result that you should be looking for is to iterate through the mirror to print out the properties of the Animal struct.
for case let (label?, value) in mirror.children {
print (label, value) // "name Derek", "species dog"
}