objective-cswiftgenericscompatibilitydowncast

Swift function overriding Objective-C method


I have an Objective-C method (declared in the class named "BaseViewModel" of my old framework) that is :

-(void) updateFromManagedObject:(__kindof NSManagedObject *)entity;

I want to use it in mutiple Swift classes. Each Swift class will use a particular subclass of NSManagedObject and inherits from "BaseViewModel". When i try to override this func like this :

override func updateFromManagedObject(entity: Person?) {
    <#code#>
}

OR

override func updateFromManagedObject(entity: Animal?) {
    <#code#>
}

the compiler returns :

Method does not override any method from its superclass

It only works with :

override func updateFromManagedObject(entity: NSManagedObject?) {
    <#code#>
}

How can I use specifics inherited types of NSManagedObject ? (Maybe with a class Generic-Type ? I try but failed too :/ )


Solution

  • The point of overriding is that the subclass method is called instead of the superclass method when the receiver is an instance of the subclass. Therefore, the subclass method's parameters must handle at least all the parameters the superclass method can handle. So the subclass method's parameters' types must be the same or more general than the parameters' types for the superclass method it overrides.