jeudi 6 juillet 2017

More efficient way for converting structure properties into dictionary

I was looking for most efficient way for creating dictionary from structures. After small research I found easy way for converting it via initialising all properties like that :

func toDictionary() -> [String : AnyObject] {
    let dictionary: [String: AnyObject] = ["firstProperty" : sth, "secondProperty" : "sth2"]
    return dictionary
}

But wait.. Do I have to initialise it every time in my structures ? They might have a loot of properties.. It gave me to think. What if I could get properties though the looping of the class somehow. Yeah, it is possible using Mirror reflection. After a while of trying I've got it - instead of function above I've written protocol which implements one function.

protocol Mirrorable {
    func toDictionary() -> [String : AnyObject]
}

Then in my structure I can simply use :

extension MyStructure/MyClass : Mirrorable {

    func toDictionary() -> [String : AnyObject] {
        let reflection = Mirror(reflecting: self).children
        var dictionary = [String : AnyObject]()
        for (label, value) in reflection {
            dictionary[label!] = value as AnyObject
        }
        return dictionary
    }
}

Curiosity does not let me to stop thinking about it. Which way would be more efficient ?





Aucun commentaire:

Enregistrer un commentaire