来自镜像自省的孩子的价值不再符合协议

问题描述

我试图了解swift的变形能力。 我有一个父类Passport,其子类(User)实现了一个协议Clonable,但是当自省子级值时,它无法通过检查child.value is Clonable。 有人可以解释吗?

extension Clonable {
    func clone() -> Self? {
        if let me = self as? SimpleInit {
            let new = type(of: me).init()
            let mirror = Mirror(reflecting: self)
            for child in mirror.children {
                if let kp = child.label,let new = new as? NSObject {
                    if child.value is Clonable,let value = child.value as? Clonable { // this should be true
                        print("cloning \(child.value) for keypath \(kp)")
                        new.setValue(value.clone(),forKeyPath: kp)
                    } else {
                        print("not cloning \(child.value) for keypath \(kp)")
                        new.setValue(child.value,forKeyPath: kp)
                    }
                }
            }
            return new as? Self
        }
        return nil
    }
}

class Passport: NSObject,Clonable,SimpleInit,Customreflectable {
    var customMirror: Mirror {
        return Mirror(self,children: ["user": user])
    }
    @objc var user: User?
    
    required override init() {
    }
    
    func printMe() {
        user?.printMe()
    }
}

class User: NSObject,children: ["name": name])
    }
    @objc var id: Int
    @objc var name: String?
    
    required override init() {
        print("init user")
        id = Int(arc4random())
    }
    
    func printMe() {
        print("id \(id) name \(name)")
    }
}


let passport = Passport()
passport.user = User()
passport.user?.name = "John"
let clone = passport.clone()

passport.printMe()
clone?.printMe()

这是输出

init user // should be called second time when user gets cloned.
not cloning Optional(<__lldb_expr_92.User: 0x6000039d6420>) for keypath user
id 2046302380 name Optional("John")
id 2046302380 name Optional("John")

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)