Malburrito
Malburrito

Reputation: 1198

Swift: How to assign a value to a variable inside an array?

I Have had quite some trouble with what is likely a beginners question in Swift:

I am trying to save some high scores to variables that I want to permanently save - based on the selected game type and game difficulty.

Preferably this should be done using a loop since in my actual code there will be many different game/difficulty combinations, so an if statement would get quite large. What I tried to do looks somewhat like this (the part where I don't know what to do is marked with a comment):

var hiScoreEasyA = 0
var hiScoreHardA = 0
var hiScoreEasyB = 0
var hiScoreHardB = 0

var currentGame = "A"
var currentDifficulty = "Easy"

var currentScore = "9999"

var newHiScore = false

func setHiScore() -> Void {
    var hiScores: [[Any]] = [
        ["A", "Easy", hiScoreEasyA],
        ["A", "Hard", hiScoreHardA],
        ["B", "Easy", hiScoreEasyB],
        ["B", "Hard", hiScoreHardB]   
    ]

    for hi in hiScores.indices {
        if (hiScores[hi][0] as! String) == currentGame && (hiScores[hi][1] as! String) == currentDifficulty {
            if (hiScores[hi][2] as! Int) < currentScore {
                newHiScore = true
                //Here I would need to assign the value of currentScore to the variable stored in hiScores[hi][2] (hiScoreEasyA)
            }
        }
    }
}

The code seems to work so far but I have not found any practical way to assign the current score to the correct high score variable.

Any ideas how to tackle this? I'd appreciate the help.

Upvotes: 0

Views: 760

Answers (1)

Sweeper
Sweeper

Reputation: 271410

You are on the wrong path. If your game has many difficulties and game types, then you should get rid of these variables:

var hiScoreEasyA = 0
var hiScoreHardA = 0
var hiScoreEasyB = 0
var hiScoreHardB = 0

and replace them with a dictionary that maps each high score category to the high score. A "high score category" is simply a difficulty and a game type combined, e.g. "easy A", "hard B":

struct HighscoreCategory: Hashable {
    let difficulty: String
    let gameType: String
}

The dictionary looks like this:

var highScores = [
    HighscoreCategory(difficulty: "Easy", gameType: "A"): 0,
    HighscoreCategory(difficulty: "Hard", gameType: "A"): 0,
    HighscoreCategory(difficulty: "Easy", gameType: "B"): 0,
    HighscoreCategory(difficulty: "Hard", gameType: "B"): 0,
]

Now to set the high score of the current game type and difficulty, you don't need any loops at all! You just do

func setHiScore() -> Void {
    let highScoreCategory = HighscoreCategory(difficulty: currentDifficulty, gameType: currentGame)
    let previousHighscore = highScores[highScoreCategory] ?? 0
    if previousHighscore < currentScore {
        newHiScore = true
        highScores[highScoreCategory] = currentScore // this is the line where you set it
    }
}

Upvotes: 4

Related Questions