Convert arrays to Dictionary

You can create a new Dictionary by mapping two sequences one is to one or by mapping a sequence of keys and values according to a custom logic; let’s take a look at both the methods:

  • Mapping two sequences (arrays) one is to one: Consider that you have two sequences personNames and ages as shown here:
 let personNames = ["Alex", "Tom", "Ravi", "Raj", "Moin"] let ages = [23, 44, 53, 14, 34]

You can create a Dictionary contacts by joining these two arrays, as follows:

let contacts = Dictionary(uniqueKeysWithValues: zip(personNames, ages)) 

The output will be this:

["Tom": 44, "Raj": 14, "Moin": 34, "Ravi": 53, "Alex": 23]
  • Create a new Dictionary by mapping an array of keys and values according to a custom logic. ...

Get Reactive Programming with Swift 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.