gpt4 book ai didi

swift - 在 Swift 中重载方法时“参数标签不正确”

转载 作者:行者123 更新时间:2023-11-28 06:24:18 25 4
gpt4 key购买 nike

我正在尝试使用以下代码在 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 行遇到错误:

调用中的参数标签不正确(有 _:playerIndex:,预期为 _:player:)

我已经查看这段代码一段时间了,但无法弄清楚为什么这行不通。有什么提示吗?

最佳答案

感谢@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

关于swift - 在 Swift 中重载方法时“参数标签不正确”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com