I have a Model class written in Objective-C, it's suppose to be inherit by sub-classes. There's a method:
- (id)deepcopy {
id newModel = [[[self class] alloc] init];
newModel.id = self.id;
// do something
return newModel;
}
sub-classes should override it with something like:
- (id)deepcopy {
id newModel = [super deepcopy];
// something else
return newModel;
}
The key is [[[self class] alloc] init], which will instance an object based on the actual class. Recently I try to upgrade this project to Swift, but could not find a way to do the same thing in Swift.
How can I do that?
I think what you're looking for is dynamicType
:
func deepcopy() -> Self {
let newModel = self.dynamicType.init()
return newModel
}
Update As for Swift 3, this seems to work:
func deepcopy() -> Self {
let newModel = type(of: self).init()
return newModel
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With