- Reactive Programming with Swift 4
- Navdeep Singh
- 147字
- 2021-06-24 18:57:58
Resolving duplicates
Swift 4 allows us to initialize a Dictionary from a sequence with duple existence of entries and manage the duplicates easily. Suppose you have an array of friends as follows:
var friends = ["Deapak", "Alex", "Ravi", "Deapak"]
Also suppose that you want to create a Dictionary with all the friends, remove duplicates, and just maintain the count of the number of occurrences that occurred in the initial friends array; you can do this by initiating a new Dictionary, as follows:
let friendsWithMultipleEntries = Dictionary(zip(friends, repeatElement(1, count: friends.count)), uniquingKeysWith: +)
The output will be the following:
["Deapak": 2, "Ravi": 1, "Alex": 1],
This helps you avoid overwriting key-value pairs, without putting in a word. The preceding code besides the shorthand +, uses zip to fix duplicate keys by adding the two contrasting values.
zip(_:_:) creates a sequence of pairs built out of two underlying sequences.
推薦閱讀
- UNIX編程藝術(shù)
- scikit-learn Cookbook
- Redis入門(mén)指南(第3版)
- Power Up Your PowToon Studio Project
- MySQL 8 DBA基礎(chǔ)教程
- PHP+MySQL網(wǎng)站開(kāi)發(fā)技術(shù)項(xiàng)目式教程(第2版)
- Java 9 Programming Blueprints
- 精通搜索分析
- Java加密與解密的藝術(shù)
- Effective Python Penetration Testing
- Keras深度學(xué)習(xí)實(shí)戰(zhàn)
- MySQL入門(mén)很輕松(微課超值版)
- 軟件體系結(jié)構(gòu)
- 智能手機(jī)故障檢測(cè)與維修從入門(mén)到精通
- 從零學(xué)Java設(shè)計(jì)模式