Game Center 提交方法导致 nil optional unwrap 错误

Game Center submission method causing nil optional unwrap error

我正在努力为我的应用添加 GameCenter 支持。我的视图控制器中有以下方法

func submitToGC(newScore: Int) {
    // Submit score to GC leaderboard
    let bestScoreInt = GKScore(leaderboardIdentifier: LEADERBOARD_ID)
    bestScoreInt.value = Int64(newScore)
    GKScore.report([bestScoreInt]) { (error) in
        if error != nil {
            print(error!.localizedDescription)
        }
    }
}

使用任何值调用时,代码会生成 "Unexpectedly found nil while unwrapping optional value" 错误。

我该如何解决这个问题?

为什么不使用 if let 来解包可选而不是强制解包?

if let highestScore = UserDefaults.standard.object(forKey: "HighestScore") as? Int{
   viewController.submitToGC(newScore: highestScore)
}

如果 submitToGC 在同一个 class 中定义,则无需使用 viewController.submitToGC 调用该函数,只需使用 submitToGC 即可。此外,最好先解包变量,然后将该值放入函数中,如下所示:

if let value = UserDefaults.standard.object(forKey: "HighestScore") as Int {
   submitToGC(newScore: value) 
}

解决方案是实例化一个 GameViewController,然后使用该实例调用它的方法。