class Person implements Cloneable {
int age;
Person(int age) {
this.age = age;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public static void main(String[] args) {
Person p = new Person(0);
Person p1 = (Person) p.clone();
p.age = 10;
System.out.println(p.age + " " + p1.age);
}
the result is 10 0 In java, we can simply use the super.clone() to implement the clone. but how can I do the same thing in swift ? must I write something like this to implement the clone in swift ?
class Person: NSObject, NSCopying {
var age: Int?
func copyWithZone(zone: NSZone) -> AnyObject {
var p = Person()
p.age = self.age
return p
}
}
it seems ok with one class, one member. but if I has a lot of child class, and every child class has different members, it will be a lot of code, I should implement clone for every child class.
in java, only one clone method in superclass, it is much more simple.