Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary from an array of objects using property of object as key for the dictionary?

With Swift is it possible to create a dictionary of [String:[Object]] from an array of objects [Object] using a property of those objects as the String key for the dictionary using swift's "map"?

class Contact:NSObject {

   var id:String = ""
   var name:String = ""
   var phone:String = ""

   init(id:String, name:String, phone:String){
      self.id = id
      self.name = name
      self.phone = phone
   }

}

var contactsArray:[Contact]
var contactsDict:[String:Contact]

contactsDict = (contactsArray as Array).map { ...WHAT GOES HERE... }
like image 279
ClayHerendeen Avatar asked Feb 07 '23 20:02

ClayHerendeen


2 Answers

Let's say you want to use id as the key for the dictionary:

var contactsArray = [Contact]()
// add to contactsArray

var contactsDict = [String: Contact]()
contactsArray.forEach {
    contactsDict[$0.id] = $0
}

The difference between map and forEach is that map returns an array. forEach doesn't return anything.

like image 84
Code Different Avatar answered Feb 10 '23 10:02

Code Different


You can achieve this via reduce in a one-line functional-style code:

let contactsDict = contactsArray.reduce([String:Contact]()) { var d = $0; d[$1.id] = $1; return d; }

This also keeps contactsDict immutable, which is the preferred way to handle variables in Swift.

Or, if you want to get fancy, you can overload the + operator for dictionaries, and make use of that:

func +<K,V>(lhs: [K:V], rhs: Contact) -> [K:V] {
    var result = lhs
    result[rhs.0] = rhs.1
    return result
}

let contactsDict = contacts.reduce([String:Contact]()) { $0 + ($1.id, $1) }
like image 43
Cristik Avatar answered Feb 10 '23 10:02

Cristik