- Reactive Programming with Swift 4
- Navdeep Singh
- 392字
- 2021-06-24 18:57:58
Key-based subscript with default value
To understand this change, let’s first try to cite why it was required in the first place; let's take a look at the following code example:
let peopleDictionary : [String: AnyObject] = ...
var name = "Unknown"
if let apiName = peopleDictionary["name"] as? String {
name = apiName
}
Basically, our goal is to get the name of the user from some Dictionary (probably coming from some API) and in case it doesn't exist, we just want to keep the default name.
There are two problems with that approach. The first is the fact that we've probably got more than just a name field, and we end up with repetitive "if let" statements that are basically just making our code less readable.
The second problem is that just for the sake of unwrapping a value, we need to come up with some artificial name for the temporary assignment (and hey, we are not good at naming stuff anyway).
So the question now is, can we do better?
The previous solution would be to use generics or extensions to modify the behavior of the existing libraries used to write some generic method to retrieve the desired value, but with Swift 4, it's now possible to access a Dictionary key and provide a default value to use if the key is missing:
let name = peopleDictionary["name", default: "Anonymous"]
We can write the same thing using nil coalescing; you can alternatively use Swift 3 to write this line:
let name = peopleDictionary["name"] ?? "Anonymous"
However, that does not work if you try to modify the value in the Dictionary rather than just reading it. Accessing the key in the Dictionary returns an optional rather than an exact value and for this reason, we can't modify a Dictionary value in place, but with Swift 4, you can write much more maintainable and succinct code, as follows:
var friends = ["Deapak", "Alex", "Ravi", "Deapak"]
var closeFriends = [String: Int]()
for friend in friends {
closeFriends[friend, default: 0] += 1
}
The preceding loop in code loops over each entry in the friends array and populates the count of each entry in the closeFriends Dictionary. Since we know that the Dictionary will always have a value, we can modify it in one line of code.
- LabVIEW2018中文版 虛擬儀器程序設(shè)計(jì)自學(xué)手冊(cè)
- Blender 3D Incredible Machines
- 青少年信息學(xué)競(jìng)賽
- 編程菜鳥(niǎo)學(xué)Python數(shù)據(jù)分析
- Python極簡(jiǎn)講義:一本書(shū)入門(mén)數(shù)據(jù)分析與機(jī)器學(xué)習(xí)
- ElasticSearch Cookbook(Second Edition)
- 打開(kāi)Go語(yǔ)言之門(mén):入門(mén)、實(shí)戰(zhàn)與進(jìn)階
- 現(xiàn)代C++編程實(shí)戰(zhàn):132個(gè)核心技巧示例(原書(shū)第2版)
- Learning YARN
- 軟件項(xiàng)目管理實(shí)用教程
- Azure Serverless Computing Cookbook
- Mastering VMware Horizon 7(Second Edition)
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- CryENGINE Game Programming with C++,C#,and Lua
- 城市信息模型平臺(tái)頂層設(shè)計(jì)與實(shí)踐