检索最佳得分游戏中心Swift
我遇到麻烦了,我无法修复与func相关的错误,以便从游戏中心检索最佳分数。如果你有分数,这个函数运行得很好,但是如果用户没有分数,它就会崩溃 有什么建议吗?代码如下:检索最佳得分游戏中心Swift,swift,game-center,game-center-leaderboard,Swift,Game Center,Game Center Leaderboard,我遇到麻烦了,我无法修复与func相关的错误,以便从游戏中心检索最佳分数。如果你有分数,这个函数运行得很好,但是如果用户没有分数,它就会崩溃 有什么建议吗?代码如下: func retrieveBestScore() { if GKLocalPlayer.localPlayer().isAuthenticated { // Initialize the leaderboard for the current local player
func retrieveBestScore() {
if GKLocalPlayer.localPlayer().isAuthenticated {
// Initialize the leaderboard for the current local player
var gkLeaderboard = GKLeaderboard(players: [GKLocalPlayer.localPlayer()])
gkLeaderboard.identifier = leaderboardID
gkLeaderboard.timeScope = GKLeaderboardTimeScope.allTime
// Load the scores
gkLeaderboard.loadScores(completionHandler: { (scores, error) -> Void in
// Get current score
var currentScore: Int64 = 0
if error == nil {
if (scores?.count)! > 0 {
currentScore = (scores![0] ).value
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)
}
}
})
}
}
谢谢大家! 根据您的代码,由于强制展开“分数”数组,您可能会遇到此问题 在结束语中尝试以下内容:
var currentScore: Int64 = 0
if error == nil, let scores = scores {
if scores.count > 0 {
currentScore = scores[0].value
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)
}
}
这里有一种第二种方法,它可以进一步压缩您的代码,我认为这应该也可以,但是如果没有看到更多的代码,很难确定,它可能需要一些小的更改
guard error == nil, let scores = scores, let currentScore = scores.first?.value else {
print("GameCenter error or no scores: \(String(describing: error)))")
return
}
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)
你能把错误回溯包括进来吗?它在第行的“error”中返回“nil”:if error==nil{…}真棒!如果你能把它标出来,那就太好了。我还将使用另一种方法进行更新,也可以使用guard语句进行更新。