Swift 2.0 Get Mirrored Superclass Properties

后端 未结 6 1817
盖世英雄少女心
盖世英雄少女心 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

    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()
        }
    }
    

提交回复
热议问题