我嘲笑了一些代码,并想提出一些(可能是架构/风格)问题。查看代码。下面的解决方案确实适用于 Playground。
import Foundation.NSError
typealias GKLeaderboardCompletion = (Int?,NSError?)->(Void)
class GKLeaderboard {
var identifier: String = ""
var localPlayerScore: Int?
func loadScoresWithCompletionHandler(completion: GKLeaderboardCompletion) {
sleep(2)
localPlayerScore = 10
completion(localPlayerScore, nil)
}
}
class GKSomeClass {
var pScore: Int? = nil
func someFunc() {
let leaderBoardRequest = GKLeaderboard()
leaderBoardRequest.identifier = "leaderboard ID"
// in order to be safe here, better to put "[unowned self]" (read more)
leaderBoardRequest.loadScoresWithCompletionHandler { [unowned self]
(scores, error) -> Void in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
} else if (scores != nil) {
// #1: Why don't you utilize the "scores"?
// #2: Does "leaderBoardRequest.localPlayerScore == scores" at the time of the callback?
// #3: What's the type of "leaderBoardRequest.localPlayerScore" here below?
// self.pScore = Int(localPlayerScore!.value)
let localPlayerScore = leaderBoardRequest.localPlayerScore
self.pScore = localPlayerScore
print("Local player's score: \(self.pScore)")
}
}
}
}
let someClass = GKSomeClass()
someClass.someFunc()