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

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.

主站蜘蛛池模板: 漳浦县| 广饶县| 阳新县| 大宁县| 西充县| 新巴尔虎右旗| 根河市| 梁平县| 南京市| 犍为县| 宝鸡市| 米泉市| 赣榆县| 濉溪县| 横峰县| 龙口市| 新营市| 宜阳县| 改则县| 深水埗区| 常州市| 朝阳市| 姜堰市| 万全县| 金平| 嘉善县| 金坛市| 宽城| 会同县| 荆州市| 唐山市| 太保市| 浦城县| 郓城县| 恭城| 林州市| 四川省| 泸西县| 海阳市| 华阴市| 新安县|