-3

I have an object array (foreign key being classId):

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

I am trying to map it to a dictionary with key of classId that looks like this:

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

Is there a good way to do this using a dictionary? My solution was to use a for loop to iterate through the array and add each object to the dictionary, but this seems inefficient.

Shivam Tripathi
  • 1,405
  • 3
  • 19
  • 37
Thrasher
  • 23
  • 3

1 Answers1

4

Swift 4 lets you instantiate a dictionary grouped by a key. Here's more detail about it. Here's an example:

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

Alternatively, you can create the dictionary with $0.classId, like so:

let dictByKeyVersionTwo = Dictionary(grouping: studentArray, by: {$0.classId})
Adrian
  • 16,233
  • 18
  • 112
  • 180