Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self class alloc equivalent in Swift

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?

like image 791
xfx Avatar asked Feb 08 '23 16:02

xfx


1 Answers

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
}
like image 179
skyline75489 Avatar answered Feb 10 '23 05:02

skyline75489