Reputation: 67
Basically, I have an array that stores the top three high scores. I want the array to be able to store each high score in itsrespective User Default. However, if a number replaces the last index for example, I need the other two numbers to change as well. In addition, repeats should be okay. It will look something like this:
1. 4
2. 4
3. 2
or
1.5
2.3
3.1
Here is my current code that doesn't work:
var highscoreArray: [Int] = [0,0,0]
var score = Int()
for i in (0...2).reversed(){
if score >= highscoreArray[i]{
highscoreArray.append(score)
highscoreArray.removeFirst()
UserDefaults.standard.set(score, forKey: "highscore\(i)")
// going to have to add user defaults here
break
} else {
continue
}
}
Upvotes: 0
Views: 80
Reputation: 3402
If you're just saving the high scores without any names or anything, I'd save them as an array of integers, so you can save and get them from UserDefaults from one key. And do something along these lines.
var highScores = UserDefaults.standard.array(forKey: "highScores") as? [Int] ?? [0, 0, 0]
let score = 1
guard score > highScores.last ?? 0 else { return }
highScores.append(score) // add new core to array
highScores.sort(by:>) // sort by value
UserDefaults.standard.set(Array(highScores.prefix(3)), forKey: "highScores")
Upvotes: 1