- Reactive Programming with Swift 4
- Navdeep Singh
- 240字
- 2021-06-24 18:57:58
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!
推薦閱讀
- Embedded Linux Projects Using Yocto Project Cookbook
- iOS 9 Game Development Essentials
- 動手玩轉Scratch3.0編程:人工智能科創教育指南
- Scala編程實戰(原書第2版)
- 可解釋機器學習:模型、方法與實踐
- Web Development with MongoDB and Node(Third Edition)
- 大話Java:程序設計從入門到精通
- Xcode 6 Essentials
- Android初級應用開發
- Socket.IO Cookbook
- Game Programming using Qt 5 Beginner's Guide
- JavaScript重難點實例精講
- Java算法從菜鳥到達人
- 算法技術手冊
- 3D Printing Designs:Fun and Functional Projects