Reflection in Swift

Or are we talking introspection?

Steven Curtis
3 min readSep 16, 2019
Does this represent Reflection, or 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

--

--