Reputation: 5557
If I have an array of objects of the form:
[{ userId: 3, data: "bla bla"} , { userId: 2, data: "bla bla"}, { userId: 3, data: "bla bla2"}, { userId: 1, data: "bla bla"}, { userId: 1, data: "bla bla2"}]
I can convert this to a dictionary with the keys being the userId
as follows:
let dict = Dictionary(grouping: myData, by: {$0.userId})
but what if I know that my user has the userId
3
and I want to create a dictionary like this:
{
key: "me",
value: [{ userId: 3, data: "bla bla"},{ userId: 3, data: "bla bla2"}],
key: "others",
value: [{ userId: 2, data: "bla bla"}, { userId: 1, data: "bla bla"}, { userId: 1, data: "bla bla2"}]
}
Upvotes: 1
Views: 152
Reputation: 272895
grouping:by:
can still help here! The key would be either "me"
or "others"
let dict = Dictionary(grouping: myData, by: {$0.userId == 3 ? "me" : "others"})
Upvotes: 3