Cade Williams
Cade Williams

Reputation: 19

How do I go about saving savings scores and high scores for a simple game in Spritekit?

I'm working on a simple game and I would like to implement a score sheet that saves scores and displays in a "high scores" section in the main menu after playing a round. Basically what I have now is a variable var Score: Int which holds an integer and that's what used inside the game to track the score, however I'd like to save 5-10 of the highest scores locally in the main menu in descending order. Any ideas on how to do this simply?

Upvotes: 0

Views: 215

Answers (1)

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

For the task as simple as yours I'd start with UserDefaults.

Store your highest scores in a sorted array, then use UserDefaults.standard.

To save the scores:

let highScores = [100, 42, 16, 10, 2]
UserDefaults.standard.set(highScores, forKey: "highScores")

The read the scores back:

if let highScores = UserDefaults.standard.object(forKey: "highScores") as? [Int] {
    print(highScores)
}

Note that if the user deletes the app from the device, the contents of user defaults will be lost.

If your data structure becomes more complex, UserDefaults will likely be no longer the best choice, in that case look into Core Data or other persistence frameworks.

Upvotes: 1

Related Questions