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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just use Dictionary(groupingBy:).

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.