Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 2.0获取镜像超类属性_Swift_Inheritance_Swift2_Mirror - Fatal编程技术网

Swift 2.0获取镜像超类属性

Swift 2.0获取镜像超类属性,swift,inheritance,swift2,mirror,Swift,Inheritance,Swift2,Mirror,我需要将类的属性作为字典来获取。为简单起见,我创建了一个协议,其默认实现如下: protocol ListsProperties{ func toDictionary() -> [String: AnyObject] } extension ListsProperties{ func toDictionary() -> [String: AnyObject] { let mirrored_object = Mirror(reflecting: sel

我需要将类的属性作为字典来获取。为简单起见,我创建了一个协议,其默认实现如下:

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

extension ListsProperties{
    func toDictionary() -> [String: AnyObject] {
        let mirrored_object = Mirror(reflecting: self)
        var dict = [String: AnyObject]()
        for (_, attr) in mirrored_object.children.enumerate() {
            if let propertyName = attr.label as String! {
                dict[propertyName] = attr.value as? AnyObject
            }
        }     

        return dict
    }
}
我的类可以符合此协议,并且将有toDictionary()方法可用。但是,如果在子类上使用该方法,这将不起作用,因为它将只生成在子类上定义的属性,而忽略父超类属性

理想情况下,我可以找到某种方法在镜像的超类上调用toDictionary()方法,因为这样就可以在自己的超类上调用toDictionary(),编译器会说,即使镜像的类符合协议,超类镜像也不符合协议

以下方法有效,但仅当只有一个超类时有效,因此还不够:

func toDictionary() -> [String: AnyObject] {
    let mirrored_object = Mirror(reflecting: self)
    var dict = [String: AnyObject]()
    for (_, attr) in mirrored_object.children.enumerate() {
        if let propertyName = attr.label as String! {
            dict[propertyName] = attr.value as? AnyObject
        }
    }

    // This is an issue as it limits to one subclass 'deep' 
    if let parent = mirrored_object.superclassMirror(){
        for (_, attr) in parent.children.enumerate() {
            if let propertyName = attr.label as String!{
                if dict[propertyName] == nil{
                    dict[propertyName] = attr.value as? AnyObject
                }
            }
        }
    }

    return dict
}

关于如何修改toDictionary()的默认实现以包括超类属性(以及超类的任何超类的属性等)的任何想法?

一个可能的解决方案是实现
toDictionary()
作为
镜像自身的一种方法,您可以递归地遍历它
到超类镜像:

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
    }
}
然后用它来实现协议扩展方法:

extension ListsProperties {
    func toDictionary() -> [String: AnyObject] {
        return Mirror(reflecting: self).toDictionary()
    }
}

通过使用协议,您需要所有的超类都实现这样的协议才能使用该函数

我将使用一个helper类,这样您就可以将任何对象传递给它

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)
    }
}
然后你可以像这样使用它

let props = ListsPropertiesHelper.toDictionary(someObject)
如果你还想写作的话

let props = someObject.toDictionary()

您可以通过调用helper类的扩展来实现该协议。

这是上面toDictionary的完整版本

它使用toDictionary()是镜像上的扩展的方法

我添加了递归,因此它可以处理任何深度的类层次结构

它在self上获得mirror.children>>self.super>>self.super.super。。等

  • 您还可以告诉它停止/不包括类,例如“NSObject” “UIViewController”
我计划自己使用它将模型对象转换为CKRecord

  • Adv:模型对象本身不需要知道CKRecord
助手方法

上面的“helper方法”也可以工作,但因为它只使用Mirror中的方法,所以将所有代码添加为Mirror的扩展也是合乎逻辑的

只要把下面所有的代码都粘贴到操场上就行了

从代码底部开始执行请参见:

//执行从这里开始

    //: Playground - noun: a place where people can play

import UIKit

//http://stackoverflow.com/questions/33900604/swift-2-0-get-mirrored-superclass-properties
//http://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/

//------------------------------------------------------------------------------------------------
//TEST DATA STRUCTURES
//------------------------------------------------------------------------------------------------
//Subclasses of NSObject
//super class of ClassASwift is NSObject
//But If we scan this tree for ivars then we dont want to include NSObject
//------------------------------------------------------------------------------------------------
class ClassNSObjectA : NSObject{
    var textA = "Some textA"
    var numA = 1111
    var dateA = NSDate()
    var arrayA  = ["A1", "A2"]
}

class ClassNSObjectB : ClassNSObjectA{
    var textB = "Some textB"
    var numB = 1111
    var dateB = NSDate()
    var arrayB  = ["B1", "B2"]
}

class ClassNSObjectC : ClassNSObjectB{
    var textC = "Some textC"
    var numC = 1111
    var dateC = NSDate()
    var arrayC  = ["C1", "C2"]
}

//------------------------------------------------------------------------------------------------
//Swift only object tree - no Root
//super class of ClassASwift is nil
//------------------------------------------------------------------------------------------------
class ClassASwift {
    var textA = "A Swift"
    var numA = 1111
    var dateA = NSDate()
    var arrayA = ["A1Swift", "A2Swift"]
}

class ClassBSwift : ClassASwift{
    var textB = "B Swift"
    var numB = 1111
    var dateB = NSDate()
    var arrayB = ["B1Swift", "B2Swift"]
}

class ClassCSwift : ClassBSwift{
    var textC = "C Swift"
    var numC = 1111
    var dateC = NSDate()
    var arrayC = ["C1Swift", "C2Swift"]
}

extension Mirror {

    //------------------------------------------------------------------------------------------------
    //How to scan a tree hierarchy of classes
    //------------------------------------------------------------------------------------------------
    /*
    TASK: we want to walk the tree from a given instance back up to the root and dump the ivars using Swift reflection.

    It came from a need to convert any object to CKRecord and have clean model objects for RealmDB.

    with the following issues:

    Some objects are Swift only - so no root object.
    So we scan up the tree recursively till super is nil
    Some objects have NSObject at the root.
    We scan up the tree and extract the ivar but we dont want to include the ivars for NSObject

    We wanted to keep our Model object as Swift as possible.
    Swift only
    You can use all the NSObject refection apis but only on NSObject classes so we need to only use Swift Reflection Mirror(reflecting:)
    ------
    We could add this objectToDictionary() method as a func on
    extension NSObject {
    scan()
    }
    But this only work for subclasses of NSObject
    ------
    Youre not allowed to have an extension on AnyObject so you cant create a swift method objectToDictionary() common to ALL Swift or NSObject Objects

    Workaround: Have a common parent for our Model objects?
    Change
    class ClassA : NSObject{...}
    class ClassASwift {...}

    class ClassA : ParentOfNSObject{...}
    class ClassASwift : ParentOfSwiftObject{...}
    but what if I want to be able to use objectToDictionary() on ALL Swift or NSObject objects
    ------

    -- Answer --
    The purpose of this method is to scan an object hierarchy and convert it to a Dictionary or CKRecord etc.

    To scan an instance we need access to Mirror and to get the objects ivars (mirror.children) and its super class ivars

    Answer was to add our extension to Mirror rather than to the object itself (dont add this method as extension to  NSObject or some ParentOfSwiftObject)

    This is similar to a Third method - a helper class
    the helperclas will just use Mirror
    the method here just combines the Mirror recursion with my extract code
    http://stackoverflow.com/questions/33900604/swift-2-0-get-mirrored-superclass-properties
    */

    func objectToDictionary(stopAtParentClassName : String?) -> [String: AnyObject]{

        //this is extension on Mirror - self is of type Mirror not the object we're analyzing
        let dict: [String: AnyObject] = objectToDictionaryForMirror(self, stopAtParentClassName: stopAtParentClassName)
        return dict

    }

    func objectToDictionaryForMirror(mirror: Mirror, stopAtParentClassName : String?) -> [String: AnyObject]{
        var dictOfIVars = [String: AnyObject]()

        let classname = "\(mirror.subjectType)"
        print("classname:\(classname)")

        //e.g. if stopAtParentClassName is nil or "NSObject"
        //stopAtParentClassName can be nil or (set and "NSObject" OR (set and not "NSbject")
        let stopAtParentClassName_ = stopAtParentClassName ?? ""

        if (classname == stopAtParentClassName_){
            //note : not really an issue for mirror.children as NSObject has none but you can parse for other reflected elements
            print("NSObject found - skipNSObjectRoot is true - SKIP this class - return empty dictionary")
        }else{

            //------------------------------------------------------------------------------------------------
            //Not NSObject or skipNSObjectRoot is false
            //------------------------------------------------------------------------------------------------
            //ITERATE OVER PROPERTIES
            //I included two ways to do this
            //v1 - dumps the properties
            //v2 - append then to a dict which is recursively appended them to outer dict
            //just remove which ever one you want
            //------------------------------------------------------------------------------------------------
            //v1
            //public typealias Child = (label: String?, value: Any)
            //note its mirror.children not self.children
            //dont use self.children : as you recursively call this method self.children will only reference the base instance
            //mirror is the recursive mirror so scanMirror(self) >> scanMirror(self.super) >> scanMirror(self.super.super) .. stop when super is nil
            for case let (label?, value) in mirror.children {
                print("PROP [\(classname)] label:[\(label)] value:[\(value)]")
            }

            //----------------------------------------------
            //v2
            // Properties of this instance:
            //self <=> Mirror
            for property in mirror.children {
                if let propertyName = property.label {
                    dictOfIVars[propertyName] = property.value as? AnyObject
                }
            }

            //------------------------------------------------------------------------------------------------
            //Mirror.children only returns ivar of current class
            //you need to walk up the tree to get all inherited properties

            //Swift object hierarchy has no root - superclassMirror() will become nil - and recursion will stop
            //NSObject object hierarchy has root NSObject - superclassMirror() will inlcude this unless stopAtParentClassName is "NSObject"
            //------------------------------------------------------------------------------------------------
            if let superclassMirror = mirror.superclassMirror() {
                let dictOfIVarsForSuperClass : [String: AnyObject] = objectToDictionaryForMirror(superclassMirror, stopAtParentClassName: stopAtParentClassName)

                //merge
                dictOfIVars.merge(dictOfIVarsForSuperClass)


            }else{
                print("class has no superclassMirror")
            }
            //---------------------------------------------------------------------
        }
        return dictOfIVars
    }
}

//Used to recursively merge superclass ivar dictionary to subclasses ivar dictionary
extension Dictionary{

    // https://github.com/terhechte/SourceKittenDaemon/blob/83dc62d3e9157b69530ed93b82b5aae9cd225427/SourceKittenDaemon/Extensions/Dictionary%2B.swift
    mutating func merge(dictionary: Dictionary<Key, Value>) {
        for (key, value) in dictionary {
            self[key] = value
        }
    }
}



func dumpDictionary(anyObject: AnyObject, stopAtParentClassName: String?){

    let mirror = Mirror(reflecting: anyObject)
    //---------------------------------------------------------------------
    //SCAN HIERARCHY - return info as a dict
    //---------------------------------------------------------------------

    let dictOfIVars = mirror.objectToDictionary(stopAtParentClassName)
    print("*****************************************************")
    print("*********** SCAN COMPLETE - DUMP DICT INFO***********")
    print("*****************************************************")

    print("dictOfIVars:\r\(dictOfIVars)")

    //------------------------------------------------------------------------------------------------
    //DEBUGGING - dump the returned dict
    //------------------------------------------------------------------------------------------------
    print("KEYS:")
    //print("dictOfIVars.keys:\(dictOfIVars.keys)")
    for key in dictOfIVars.keys.sort(){
        print(key)
    }
    //------------------------------------------------------------------------------------------------
    print("dictOfIVars.keys.count:\(dictOfIVars.keys.count)")
    //------------------------------------------------------------------------------------------------

}


//EXECUTION STARTS HERE IF YOU PASTE IN TO PLAYGROUND




print("======================================================================")
print("START TESTS - open console below ")
print("======================================================================")

//------------------------------------------------------------------------------------------------
//NSObject class hierarchy
//------------------------------------------------------------------------------------------------

print("")
print("=====================================================================================================================")
print("========== TEST 1: recursively iterate up tree of NSObject subclasses - include root object 'NSObject' in scan")
print("=====================================================================================================================")

let instanceC : ClassNSObjectB = ClassNSObjectC()
//Dont include NSObject root in parse
dumpDictionary(instanceC, stopAtParentClassName: "NSObject")

print("")
print("=====================================================================================================================")
print("========== TEST 2: recursively iterate up tree of NSObject subclasses - DO NOT include root object 'NSObject' in scan")
print("=====================================================================================================================")
//Do include NSObject
dumpDictionary(instanceC, stopAtParentClassName: nil)

//note were only dumping mirror.children in this example and NSObject doesnt have any but added for completeness.
//could dump all sub classes of UIViewController - but not include the UIViewController class ivars

//------------------------------------------------------------------------------------------------
//Switft class hierarchy - no root class
//------------------------------------------------------------------------------------------------
print("")
print("======================================================================================================================")
print("========== TEST 3: recursively iterate up tree of Swift subclasses")
print("======================================================================================================================")
let classBSwift : ClassBSwift = ClassCSwift()
dumpDictionary(classBSwift, stopAtParentClassName: nil)

您只需在所有
超类镜像中循环即可获得属性。不管有多少层

var镜像:镜像?=镜子(反射:儿童)
重复{
用于镜像子对象中的属性{
打印(“属性:\(属性)”)
}
mirror=mirror?.superclassmrror()
}一面镜子!=无

这是我的实现

  • 支持继承链
  • 支持嵌套对象
  • 打开可选项(如果有的话)
  • 支持具有rawValue的枚举
  • 支持阵列

我的解决办法是使用

Mirror(self, children: properties, ancestorRepresentation: Mirror.AncestorRepresentation.generated)
而不是

Mirror(representing: self)

properties是一个dictionnarylateral对象,其中包含要镜像的属性。

在if case.some(let value)行出现错误=可选//错误是-将未声明的标识符和case let rawRepresentable用作rawRepresentable://错误是:协议“rawRepresentable”只能用作泛型约束,因为它具有自约束或关联约束
class BaseUser: Serializable { let id: Int = 1 }
class User: BaseUser { let name: String = "Aryan" }

let user = User()
print(user.serialize())   // {"id": 1, "name": "Aryan"}
print([user].serialize()) // [{"id": 1, "name": "Aryan"}]
Mirror(self, children: properties, ancestorRepresentation: Mirror.AncestorRepresentation.generated)
Mirror(representing: self)