Click here to Skip to main content
15,867,765 members
Articles / Desktop Programming / Cocoa

Optional Chaining with Dictionaries (in Swift)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Jan 2015CPOL1 min read 9.6K   1
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)


Written By
Team Leader
United Kingdom United Kingdom
My day job is mostly working in C++ with a bit of C#. I write a fair amount of command line based tools and really wish they could have a GUI front-end to them hence why I spend my spare time working with WPF.

I started a blog few years back but didn't do a lot with it. I've started describing some of the interesting programming things I come across on it. Please take a look.

Comments and Discussions

 
GeneralMy vote of 5 Pin
ctietze29-Jan-15 3:29
ctietze29-Jan-15 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.