Thrasher
Thrasher

Reputation: 23

Swift 4 map a dictionary with [String:[Object]] more efficiently

I am reading an array of objects that looks like this:

[Group(id:"g001", name:"Group 1", projects:[Project(id:"p001", name:"Project 1"), Project(id:"p002", name:"Project 2")]), Group(id:"g002", name:"Group 2", projects:[Project(id:"p003", name:"Project 3")])]

Right now, I am using two for-loops to get to the projects, and then adding them to the dictionary like this:

var dictionary: Dictionary = [String: [Project]]()
for group in groups{
  let groupId = group.id
  for project in group.projects {
      dictionary[groupId, default: []].append(project)
  }
}

It works, but it seems like with Swift 4 it can be done more efficiently, and more quickly. What is the best way to use map or reduce with this type of array and dictionary?

Upvotes: 0

Views: 438

Answers (1)

user2908517
user2908517

Reputation: 518

Assuming that group id is unique:

var dictionary = Dictionary(uniqueKeysWithValues: groups.map{($0.id, $0.projects)})

Upvotes: 1

Related Questions