Equivalent to self class alloc in Swift

I have a Model class written in Objective-C, it must be inherited by subclasses. There is a method:

- (id)deepcopy {
    id newModel = [[[self class] alloc] init];
    newModel.id = self.id;
    // do something
    return newModel;
}
Routines

should redefine it as follows:

- (id)deepcopy {
    id newModel = [super deepcopy];
    // something else
    return newModel;
}

The key is [[[self class] alloc] init] , which will be an instance of an object based on the actual class. I recently try to upgrade this project to Swift, but could not find a way to do the same in Swift.

How can i do this?

+4
source share
1 answer

I think you are looking for dynamicType:

func deepcopy() -> Self {
    let newModel = self.dynamicType.init()
    return newModel
}

Update As for Swift 3, this works:

func deepcopy() -> Self {
    let newModel = type(of: self).init()
    return newModel
}
+7
source

All Articles