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
By using a protocol, you require that all the superclasses implement such a protocol to be able to use the function.
I would use a helper class, so that you can pass any object to it.
class ListsPropertiesHelper {
static func toDictionary(mirrored_object: Mirror) -> [String: AnyObject] {
var dict = [String: AnyObject]()
for (_, attr) in mirrored_object.children.enumerate() {
if let propertyName = attr.label as String! {
dict[propertyName] = attr.value as? AnyObject
}
}
if let parent = mirrored_object.superclassMirror() {
let dict2 = toDictionary(parent)
for (key,value) in dict2 {
dict.updateValue(value, forKey:key)
}
}
return dict
}
static func toDictionary(obj: AnyObject) -> [String: AnyObject] {
let mirrored_object = Mirror(reflecting: obj)
return self.toDictionary(mirrored_object)
}
}
Then you can use it like
let props = ListsPropertiesHelper.toDictionary(someObject)
If you still want to be able to write
let props = someObject.toDictionary()
you can implement the protocol with the extension calling the helper class.