2

I have a Realm Object class called Performance which looks like this

class Performance: Object {

@objc dynamic var move = ""
@objc dynamic var score = 0

}

and when I print the results of the Realm object I get something like this

 [Performance {
  move = Run;
  score = 3;
}, Performance {
  move = Walk;
  score = 3;
}, Performance {
  move = Run;
  score = 2;
}]

Then I try to convert the realm results into an Array so that I can merge the performances with the same move and add their score so that I can show the user which of their move has the highest and lowest scores.

I would want to know if there is any chance where I can merge the Performance with the same move and add their score so that the array would look like this.

[Performance {
move = Run;
score = 5;
}, Performance {
move = Walk;
score = 3;
}]

I have tried few solutions like One, two and three.

But they are not really helpful for my problem.

Dev_A
  • 23
  • 2

1 Answers1

1

You could iterate through the array and create a dictionary with your move type being the key.

For example:

var totals: [MoveType: Int] = [:]
for item in performances {
    totals[item.move] = item.score + (totals[item.move] ?? 0)
}

For each item, this will add the score to the dictionary for the relevant move type, creating a new dictionary entry if it's the first item with that move type.

Andy
  • 723
  • 9
  • 24