Swift 2.0 Get Mirrored Superclass Properties

后端 未结 6 1843
盖世英雄少女心
盖世英雄少女心 2020-12-20 16:16

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         


        
6条回答
  •  余生分开走
    2020-12-20 17:04

    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.

提交回复
热议问题