简体   繁体   English

Swift - 根据自定义条件将数组转换为字典

[英]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:我可以将其转换为以userId为键的字典,如下所示:

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:但是如果我知道我的用户有userId 3并且我想创建一个这样的字典怎么办:

{
   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! grouping:by:在这里仍然可以提供帮助! The key would be either "me" or "others"关键是"me""others"

let dict = Dictionary(grouping: myData, by: {$0.userId == 3 ? "me" : "others"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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