官术网_书友最值得收藏!

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. Suppose you have two arrays- one with Strings representing all the odd numbers in words and other one with integers from 1 to 10:
let oddKeys = ["one", "three", "five", "seven", "nine"]
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • Now, consider that you want to create a Dictionary in which you want to map the String values to corresponding int values; you can do this as follows:
numbers = numbers.filter { $0 % 2 != 0 }
let oddDictionary = Dictionary(uniqueKeysWithValues: zip(oddKeys, numbers))
print(oddDictionary)
  • The output will be this:
["six": 6, "four": 4, "eight": 8, "ten": 10, "two": 2]

Easy, isn’t it!

主站蜘蛛池模板: 鄄城县| 章丘市| 博兴县| 定结县| 湘潭县| 金华市| 德格县| 苗栗县| 隆林| 丰台区| 乌兰县| 西藏| 夏邑县| 双牌县| 凭祥市| 虞城县| 陵川县| 平阴县| 阿拉尔市| 安义县| 五河县| 崇文区| 淮南市| 巴塘县| 莱州市| 财经| 武陟县| 噶尔县| 香河县| 寻乌县| 南郑县| 黑龙江省| 宜川县| 探索| 江川县| 玉门市| 黔东| 元氏县| 吉安县| 罗江县| 安西县|