I need to get the properties of my class as a dictionary. For simplicity, I created a protocol which has a default implementation as follows:
protocol ListsP
One possible solution would be to implement toDictionary()
as a method of Mirror
itself, so that you can traverse recursively
to the superclass mirror:
extension Mirror {
func toDictionary() -> [String: AnyObject] {
var dict = [String: AnyObject]()
// Properties of this instance:
for attr in self.children {
if let propertyName = attr.label {
dict[propertyName] = attr.value as? AnyObject
}
}
// Add properties of superclass:
if let parent = self.superclassMirror() {
for (propertyName, value) in parent.toDictionary() {
dict[propertyName] = value
}
}
return dict
}
}
and then use that to implement the protocol extension method:
extension ListsProperties {
func toDictionary() -> [String: AnyObject] {
return Mirror(reflecting: self).toDictionary()
}
}