Swift Language Reflection Basic Usage for Mirror


Creating the class to be the subject of the Mirror

class Project {
    var title: String = ""
    var id: Int = 0
    var platform: String = ""
    var version: Int = 0
    var info: String?

Creating an instance that will actually be the subject of the mirror. Also here you can add values to the properties of the Project class.

let sampleProject = Project()
sampleProject.title = "MirrorMirror"
sampleProject.id = 199
sampleProject.platform = "iOS"
sampleProject.version = 2
sampleProject.info = "test app for Reflection"

The code below shows the creating of Mirror instance. The children property of the mirror is a AnyForwardCollection<Child> where Child is typealias tuple for subject's property and value. Child had a label: String and value: Any.

let projectMirror = Mirror(reflecting: sampleProject)
let properties = projectMirror.children

print(properties.count)        //5
print(properties.first?.label) //Optional("title")
print(properties.first!.value) //MirrorMirror

for property in properties {

Output in Playground or Console in Xcode for the for loop above.

info:Optional("test app for Reflection")

Tested in Playground on Xcode 8 beta 2