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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset