Swift 4通过外键将数组映射到字典

时间:2018-02-08 02:43:47

标签: ios arrays swift dictionary mapping

我有一个对象数组(外键是classId):

let studentArray = [Student(id:3, name:"John", classId:1), Student(id:4, name:"Jane", classId:1), Student(id:5, name:"Bill", classId:2)]

我正在尝试将其映射到具有classId键的字典,如下所示:

[1:[Student], 2:[Student]]

使用字典有没有好办法呢? 我的解决方案是使用for循环迭代数组并将每个对象添加到字典中,但这似乎效率低下。

1 个答案:

答案 0 :(得分:4)

Swift 4允许您实例化按键分组的字典。这是关于它的more detail。这是一个例子:

Date                Workout.Name    Exercise.Name               Set.Order  TotalWeight
6/29/2017 9:50      Chest 1         barbell bench press         0          165
7/4/2017 10:23      Chest 1         barbell bench press         0          165
11/14/2017 1:22     Chest 1         barbell bench press         0          240

或者,您可以使用let studentArray = [Student(id:3, name:"John", classId:1), Student(id:4, name:"Jane", classId:1), Student(id:5, name:"Bill", classId:2)] let dictByKeyVersionOne = Dictionary(grouping: studentArray, by: {student in student.classId}) 创建字典,如下所示:

$0.classId