xfx xfx - 2 months ago 34
iOS Question

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?

Answer

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
}