gpt4 book ai didi

ios - 试图从类中获取值的下标错误

转载 作者:行者123 更新时间:2023-11-28 12:27:22 25 4
gpt4 key购买 nike

我正在尝试将一个类中的所有值加在一起。这是我的代码:

 var allPlayersArray: [allPlayersIngame] = []

class allPlayersIngame {
let username: String
let uid: String
var score: Int

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

var totalScore = 0
for playerScore in self.allPlayersArray{
if let score = self.allPlayersArray[playerScore].score{
}//error
totalScore += allPlayersArray[playerScore].score
}//error
self.averageScore = totalScore / self.allPlayersArray.count
}

错误如下:

Cannot subscript a value of type '[vc.allPlayersIngame]' with an index of type 'vc.allPlayersIngame'

我的方法是遍历每个数组元素并获得它们的分数。好吧,结果并不理想。

最佳答案

您混淆了基于 index 和基于 itemfor 循环

它是(索引基于)

for index in 0..<self.allPlayersArray.count {
totalScore += allPlayersArray[index].score
}
self.averageScore = totalScore / self.allPlayersArray.count

或(基于项目)

for playerScore in self.allPlayersArray {
totalScore += playerScore.score
}
self.averageScore = totalScore / self.allPlayersArray.count

或(无循环)

let totalScore = self.allPlayersArray.map({ $0.score }).reduce(0, { $0 + $1 })

关于ios - 试图从类中获取值的下标错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003162/

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