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 ...

Get Reactive Programming with Swift 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.