Basic Usage for Mirror
suggest changeCreating 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 creates a Mirror. Its children property is an AnyCollection<Child>, where Child is a typealias for a tuple of the subject’s property and value. Child has a label: String? and a 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents