Swift Academy · Lesson

Reflection with Mirror

Inspect properties of any value at runtime.

Lesson 3 of 413 steps

Reflection with Mirror is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

What Is Mirror?

Mirror is Swift runtime reflection: it lets you inspect a value structure — its properties and their values — without knowing the concrete type at compile time.

Creating a Mirror

Pass any value to Mirror(reflecting:):

struct Point { let x: Int; let y: Int }
let m = Mirror(reflecting: Point(x: 1, y: 2))
print(m.children.count)  // 2

Iterating children

Each child is a label/value pair:

struct User { let name: String; let age: Int }
let m = Mirror(reflecting: User(name: "Ann", age: 30))
for child in m.children {
    print("\(child.label ?? "?") = \(child.value)")
}
// name = Ann
// age = 30

Building a Dictionary of Fields

Reflection can flatten a struct into a dictionary:

struct Config { let host: String; let port: Int }
let m = Mirror(reflecting: Config(host: "x", port: 80))
var dict: [String: Any] = [:]
for c in m.children { if let l = c.label { dict[l] = c.value } }
print(dict["port"]!)  // 80

displayStyle

Mirror reports a displayStyle — .struct, .class, .enum, .tuple, .collection, etc. — so you can branch on the kind of value.

Inspecting the Display Style

Detect what kind of value you are reflecting:

struct S { let a = 1 }
let m = Mirror(reflecting: S())
if m.displayStyle == .struct {
    print("it is a struct with \(m.children.count) field(s)")
}
// it is a struct with 1 field(s)

Reflecting a Tuple

Tuples expose positional children:

let m = Mirror(reflecting: (10, "hi", true))
for c in m.children { print(c.value) }
// 10
// hi
// true

Reflecting Enums

For enum cases with associated values, the child holds the payload:

enum Result2 { case ok(Int); case fail(String) }
let m = Mirror(reflecting: Result2.ok(42))
print(m.children.first?.value ?? "none")  // 42

A Generic Field Printer

Reflection enables type-agnostic utilities:

func dump2(_ value: Any) {
    for c in Mirror(reflecting: value).children {
        print("\(c.label ?? "_"): \(c.value)")
    }
}
struct Car { let make: String; let year: Int }
dump2(Car(make: "Mini", year: 2020))
// make: Mini
// year: 2020

Reflection Costs and Limits

Mirror is slower than direct access and read-only — you cannot set properties through it. Use it for debugging, logging, and serialization helpers, not hot paths.

struct P { let v: Int }
let m = Mirror(reflecting: P(v: 5))
print(m.children.first!.value)  // 5  (read only)

Casting Reflected Values

Children values are typed as Any; cast them back when you need the concrete type:

struct Box { let count: Int; let label: String }
let m = Mirror(reflecting: Box(count: 3, label: "hi"))
for c in m.children {
    if let n = c.value as? Int { print("int: \(n)") }
    if let s = c.value as? String { print("str: \(s)") }
}
// int: 3
// str: hi

Quick Check

What does iterating Mirror(reflecting: value).children give you?

Recap

You learned Mirror:

  • Mirror(reflecting:) inspects a value at runtime
  • children yields label/value pairs
  • displayStyle tells you struct / class / enum / tuple / collection
  • Read-only and slower — great for debugging and serialization, not hot paths

Next: building debug-friendly types.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Reflection with Mirror” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Reflection with Mirror”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Reflection with Mirror”?

Inspect properties of any value at runtime. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Reflection with Mirror” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. CustomStringConvertible
  2. CustomDebugStringConvertible
  3. Reflection with Mirror
  4. Building Debug-Friendly Types
← Back to Swift Academy