Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

PlayingCard inherits from Card

Given the two functions with the same name:

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

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

It is throwing an Error Saying : Overriding method with selector 'match:' has incompatible type '([PlayingCard]) -> Int'

Why??? Its two functions with same name but two different kind of parameters why is it still asking for override?? If I do that then even that is called as Error

like image 666
sriram hegde Avatar asked Jul 25 '15 17:07

sriram hegde


1 Answers

Can you do this?

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!

Specifically you can if Card does not extends 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 extends NSObject.

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

Then you get the error!

It looks like overloading only works on "pure" Swift classes.

like image 51
Luca Angeletti Avatar answered Sep 28 '22 05:09

Luca Angeletti