0

I want using Mirror to add to the parent class without having to add a clone of the child's class

Do you think this is possible?

base class :

class BaseModel {

 func clone() -> BaseModel {

          let mirror = Mirror(reflection : self)
           for (lable , value) in mirror.children {

             }
          return ...
   }
}

subclass :

class UserModel:BaseModel {

   var name:String!
   var family:String!

}

usage :

 let cloneModel = self.userModel.clone()
Farshid roohi
  • 722
  • 9
  • 23
  • There is no need to do this as you can create the copy of the object in the swift.Simply use struct to create your model and then assigning it to new variable automatically creates a new copy of the assigning model to the new variable. – Y_Y Jun 24 '18 at 10:49
  • Y_Y thamks ,the project i can not change the structure of the models – Farshid roohi Jun 24 '18 at 11:25

1 Answers1

0

You have to implement NSCopying protocol and override copy(with:) function:

class BaseModel: NSCopying {

   var xx: String?
   var yy: Int?

   private init(xx: String, yy: Int) {
       self.xx = xx
       self.yy = yy
   }

   func copy(with zone: NSZone? = nil) -> Any {
       let copy = BaseModel(xx: xx, yy: yy)
       return copy
   }
}

Usage:

let clone = model.copy() as! BaseModel

Or you can refer to this answer: https://stackoverflow.com/a/32113575/3882414

rami
  • 129
  • 2
  • 10