Reputation: 5599
I am trying to do method overloading in Swift with the following code:
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)
}
}
I am getting an error on the self.setScore
line:
Incorrect argument labels in call (have _:playerIndex:, expected _:player:)
I have been looking at this code for a while now but can't figure out why this wouldn't work. Any hints?
Upvotes: 1
Views: 1292
Reputation: 5599
Thanks to @Hamish for pointing me in the right direction.
Turns out that the compiler message is rather misleading. The problem is that every method that calls a mutating
method must be mutating
itself. So this solves the problem:
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)
}
}
Also see .sort in protocol extension is not working
Upvotes: 1