简体   繁体   中英

Swift - Convert Array to Dictionary Based on Custom Condition

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"}]
}

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"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM