iOS Mirror

Meghana Trivedi
2 min readJun 18, 2022
Mirror Reflection in iOS Swift

A representation of the substructure and display style of an instance of any type.

Swift places a lot of emphasis on static typing, but it also supports rich metadata about types, which allows code to inspect and manipulate arbitrary values at runtime. This is exposed to Swift programmers through the Mirror API

What is Reflection?

Reflection in Swift comes down to printing out metadata information about a given value.

Using Mirror on common types

  1. Reflecting a class
  2. Reflecting a struct
  3. Reflecting a tuple
  4. Reflecting an enum

Reflecting a class

final class ArticlePublisher {
let blogTitle: String = “iOS Mirror”
}
let publisher = ArticlePublisher()
Mirror(reflecting: publisher).children.forEach {
child in print(“Found child ‘\(child.label ?? “”)’ with value ‘\(child.value)’”)
}

output:
Found child ‘blogTitle’ with value ‘iOS Mirror’

Mirror Reflection in iOS Swift

Reflecting a struct

struct userModel{
var firstName: String
var lastName: String
var emailId: String
var age: Int
}

let user = userModel(firstName : “Meghana” , lastName: “Trivedi” ,emailId: ”meghanatrivedi92@gmail.com” , age: 26)

let mirror = Mirror(reflecting: user)

for children in mirror{
print(“Found child as \(children.label ?? “”) with value \(children.value)”)
}

output:

Found child as firstName with value Meghana
Found child as lastName with value Trivedi
Found child as emailId with value meghanatrivedi92@gmail.com
Found child as age with value 26

Reflecting a tuple

let tuple = (“Meghana”, “iOS Developer”)
Mirror(reflecting: tuple).children.forEach {
child in print(“Found child ‘\(child.label ?? “”)’ with value ‘\(child.value)’”)
}

output:

Found child ‘.0’ with value ‘Meghana’
Found child ‘.1’ with value ‘iOS Developer’

Reflecting an enum

enum ArticleState{
case scheduled(Date)
case Published
}

let scheduledState = ArticleState.scheduled(Date())
Mirror(reflecting: scheduledState).children.forEach {
child in print(“Found child ‘\(child.label ?? “”)’ with value ‘\(child.value)’”)
}

let publishedState = ArticleState.published
Mirror(reflecting: publishedState).children.forEach {
child in print(“Found child ‘\(child.label ?? “”)’ with value ‘\(child.value)’”)
}

output:

Found child ‘scheduled’ with value ‘2021–12–21 08:16:48 +0000’
-

--

--

Meghana Trivedi

Meghana Trivedi is a Software Developer who helps Startups and local Entrepreneur develop their idea into product and reach the right audience.