我正在尝试使用以下代码在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:)
我一直在看这段代码一段时间,但无法弄清楚为什么这不起作用。任何提示?
答案 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)
}
}