Swift中的方法重载时'参数标签不正确'

时间:2017-02-24 18:48:27

标签: swift parameters overloading

我正在尝试使用以下代码在Swift中进行方法重载:

struct Game {
    private let players: [UserProfile] //set in init()
    private var scores: [Int] = []

    mutating func setScore(_ score: Int, playerIndex: Int) {

        //... stuff happening ...

        self.scores[playerIndex] = score
    }

    func setScore(_ score: Int, player: UserProfile) {
        guard let playerIndex = self.players.index(of: player) else {
            return
        }

        self.setScore(score, playerIndex: playerIndex)
    }
}

我在self.setScore行收到错误:

Incorrect argument labels in call (have _:playerIndex:, expected _:player:)

我一直在看这段代码一段时间,但无法弄清楚为什么这不起作用。任何提示?

1 个答案:

答案 0 :(得分:1)

感谢@Hamish指出我正确的方向。

原来,编译器消息相当误导。问题是每个调用mutating方法的方法本身必须是mutating。所以这解决了这个问题:

struct Game {
    private let players: [UserProfile] //set in init()
    private var scores: [Int] = []

    mutating func setScore(_ score: Int, playerIndex: Int) {

        //... stuff happening ...

        self.scores[playerIndex] = score
    }

    mutating func setScore(_ score: Int, player: UserProfile) {
        guard let playerIndex = self.players.index(of: player) else {
            return
        }

        self.setScore(score, playerIndex: playerIndex)
    }
}

另见.sort in protocol extension is not working