N N
N N

Reputation: 1638

Issues with overriding methods in swift

I am new in swift and getting some errors in following code:

class Player {
    var  name: String
    var score: Int

    func playerInfo()->(String, Int){
        return (name, score)
    }

    init(name:String, score:Int){
        self.name  = name
        self.score = score
    }
}

final class GoldPlayer : Player {
    var status: String
    init(name: String, score: Int, status: String) {
        self.status = "Gold"
        super.init(name: name, score: score)
    }
    func playerInfo() -> (String, Int, String) {
        return (name, score, status)

    }

}

Error is on line where I override playerInfo() -> (String, Int, String) If I type override in front of method, I get error message method does not override any methods from its superclass. If I won't type override, I get error message when I call that method from a class instance, that says ambiguous use of playerInfo(). What am I doing wrong? Thanks in advance!

Upvotes: 2

Views: 131

Answers (2)

Ankit Goel
Ankit Goel

Reputation: 6495

As mentioned in Tikhonov's answer you cannot override the method because they have different return types. So remove the override keyword.

The actual problem here is that the compiler is not able to determine which method you are trying to call. So you just need to specify the type of the variable in which you will store the return value.

let instance = GoldPlayer()

let x: (String, Int, String) = instance.playerInfo()

If you don't explicitly specify the type of the variable which stores the result of the function then you will get the error "Ambiguous use of playInfo" as compiler can only differentiate these two functions based on their return type and you didn't provide that info.

Upvotes: 3

Tikhonov Aleksandr
Tikhonov Aleksandr

Reputation: 14329

Because compiler doesn't know what type would you like to use.

You can specify the type exactly

let goldPlayer = GoldPlayer(name: "Vasa", score: 33, status: "high")
let result: (String, Int, String)  = goldPlayer.playerInfo()

And you cannot use override keyword, because you functions have different signature. At first case func f()-> (String, Int), at second case func f() -> (String, Int, String). You could use override if the second function has return type (String, Int)

Upvotes: 2

Related Questions