Swift, can I override a method with a more specific derived parameter type

PlayingCard inherits a card

For two functions with the same name:

func match(othercards : [PlayingCard]) -> Int { return 2 } func match(othercards : [Card]) -> Int { return 2 } 

It throws an error: "The overriding method with the match: selector is of an incompatible type" ([PlayingCard]) β†’ Int '

Why??? Its two functions with the same name, but two different types of parameters, why is it still asking to override? If I do this, even this is called Error

+5
source share
3 answers

Since PlaingCard is inherited from the Card, you are not allowed to redefine the method in this way.

Think about what happens if you try to match a PlayingCard instance. Which of the two methods would he name? This would be ambiguous and therefore not allowed.

In this case, one solution is to change the name of the method, which takes a more specific type. eg.

  func matchPlayingCard(othercards : [PlayingCard]) -> Int { return 2 } 
0
source

Can you do it?

 class Card { func match(othercards : [Card]) -> Int { return 2 // I changed the return value just to test it } } class PlayingCard : Card { func match(othercards : [PlayingCard]) -> Int { return 1 } } 

Yes

In particular, you can, if the Card does not extend NSObject .

 class Card { func match(othercards : [Card]) -> Int { return 2 // I changed the return value just to test it } } 

On the other hand, if Card continues to NSObject .

 class Card : NSObject { func match(othercards : [Card]) -> Int { return 2 // I changed the return value just to test it } } 

Then you will get an error message!

It seems that overloading only works with pure Swift classes.

+2
source

The Swift compiler should see both PlayingCard and Card as the same type. If you inherit (either by subtype or protocol (under certain circumstances)), this may explain this.

Although this can be thought of as a smell of code, you can also check the type at runtime and use only one function, as in the accepted answer here: Check if the object is a given type in Swift .

Some patterns that can be applied are given in this explanation of a similar example - although the question is about C #, similar object-oriented methods can be applied: the override method with a derived parameter instead of a base .

+1
source

All Articles