w461
w461

Reputation: 2678

SWIFT still fighting to assign a value to a nested array within a class

This carries on my last question struggling with value assignment to optional class variable, for which David provided me a good hint to a similar problem. After numerous iterations I now came up with a different approach, however, it still fails and I have no idea why (and basically what happens)

I have the class definitions

struct HighScores: Codable {
    var Scores:Int
    var highscoreRecord: [HighscoreRecord]
}

struct HighscoreRecord: Codable {
    var Rank:Int
    var Date:String?
    var avDuration:Float?
    var Score:Int?
    var Tries:Int?
}

In the view controller I have declared a variable of type HighScores, which may read the data from a JSON file or which may be initialized when setting the first high score.

class GameplayViewController: UIViewController {

    var jsonResult: HighScores?

   ...

    if firstHighscore == 1 {
        jsonResult?.Scores = 1
        jsonResult?.highscoreRecord.append(HighscoreRecord(Rank: 1, Date: formatter.string(from: dateStart), avDuration: Float(lblSpeed.text ?? "0.0"), Score: Int(lblRatio.text ?? "0"), Tries: hits + misses))
...
    print(jsonResult)

This compiles and also runs. However, if I monitor the jsonResult variable, it still shows nil after assigning the Scores and and highscoreRecord values.

What happens, why can I assign a value without an error and without actually assigning it? And first and foremost, how do I get my values into jsonResult?

Cheers

Upvotes: 1

Views: 93

Answers (1)

Joby Ingram-Dodd
Joby Ingram-Dodd

Reputation: 730

So following on from the comments above if you changed the code to be something along the lines of this you create the instance of the struct and add the values.

var jsonResult: HighScores?

    if firstHighscore == 1 {
        jsonResult = HighScores(Scores: 1, highscoreRecord: [HighscoreRecord(Rank: 1, Date: "your date", avDuration: 0.0, Score: 0, Tries: 0)])
    } 

once created you can add more highscorerecords to the array as needed, using the append method.

Upvotes: 1

Related Questions