Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Cocoa

Optional Chaining with Dictionaries (in Swift)

5.00/5 (1 vote)
28 Jan 2015CPOL1 min read 10.4K  
Optional Chaining with Dictionaries (in Swift)

Whilst learning Swift and SpriteKit, I came across an issue with the documentation for SKNode.userData. In an early XCode beta, it was specified as an implicitly unwrapped optional whereas now it is clearly an optional.

JavaScript
var node = SKNode()
...
if let userData = node.userData
{
    if let value = userData["key']
      // do something with value
}

Once I discovered optional chaining, I was able to shorten this to:

JavaScript
var node = SKNode()
...
if let value = userData?["key"]
{
  // do something with value
}

In essence, use optional chaining to check for existence of userData.

This is not something I've seen written about before. Optional chaining of subscripts is mentioned in The Swift Programming Language book but this only appears in reference to providing a custom subscript operator for a class as opposed to using it with stock types and a brief mention in connection with Dictionaries when the key is not present is also made, e.g.

JavaScript
var dict = ["foo": "hello"]
dict["bar"]? = "world"

The latter is interesting as without the '?' then "world" will be inserted along with the creation of the "bar" key whereas using optional chaining, the key must already exist.

Both forms can be combined, e.g.

JavaScript
var dict : [String : String]?
dict?["bar"]?= "world"

which will only insert world if the key "bar" exists and dict exists.

The use of optional chaining with subscript types can lead, like lots of other uses of optional chaining to more readable & succinct code, this is just another example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)