Swift Language Basic Usage for Mirror


Example

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
print()

for property in properties {
    print("\(property.label!):\(property.value)")
}

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

title:MirrorMirror
id:199
platform:iOS
version:2
info:Optional("test app for Reflection")

Tested in Playground on Xcode 8 beta 2