2

My class

class ScoreModel {
    var playerId: Int?
    var holeScores: [HoleScore]?
}

Other Class

class HoleScore {
    var holeScore: Int?
}

I have these classes one is ScoreModel class which can have Array of objects of HoleScore

let scoreList = [ScoreModel]()
scoreList[0].holeScores![0].holeScore = 3

When i update or change holeScore for scoreList[0].holeScores[0] it changes it for all the scoreList[forAllIndexes].holeScores[0]. I just want to change the inner array prams for given index of outer array but it changes all the holeScore values when ever update.

5
  • 5
    Remember that class has reference semantics, how scoreList filled? Commented Apr 24, 2018 at 8:19
  • 1
    It looks like you appended always the same HoleScore instance to holeScores Commented Apr 24, 2018 at 8:20
  • Please check holeScores size Commented Apr 24, 2018 at 8:21
  • 1
    Better change to struct if you are not familiar on dealing with reference type Commented Apr 24, 2018 at 8:22
  • thank u @Tj3n using struct solved my problem Commented Apr 25, 2018 at 5:40

2 Answers 2

2

This appends the same object , so change in one reflects to others

var item = HoleScore()

for i in 0...5
{
    item. holeScore = i

    scoreList[0].holeScores.append(item)
}

//

This appends different objects , so change in one doesn't reflects to others

for i in 0...5
{
    var item = HoleScore()

    item. holeScore = i

    scoreList[0].holeScores.append(item)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just solved my problem converting my classes to struct .I just did not know how to deal with this reference types in a nested sub arrays .So I used struct

   struct ScoreModel {
        var playerId: Int?
        var holeScores: [HoleScore]?
    }

   struct HoleScore {
    var holeScore: Int?
   }

Now setting value for a specific inner index will not effect others

let scoreList = [ScoreModel]()
scoreList[0].holeScores![0].holeScore = 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.