Swift 2.0: Let’s try?

When I read the Release Notes for Xcode 7 Beta 6, I got immediately excited by these three things:

One thing I did NOT tweet about is that I was kind of confused by the first and biggest Swift change mentioned:

Screen Shot 2015-08-26 at 4.48.03 AM

I showed some code to @allonsykrakenย yesterday, and he refactored it in an awesome way with try?. This really helpedย the importance of try? sink in for me, so I wanted to share it here.

JSON Parsing with try

The use-case is… you guessed it! JSON Parsing. Here is the code I had for a simple todo app:

Issue 1: Unexpected Throwing

First, notice that NSJSONSerialization‘s JSONObjectWithData class method throws an error. This actually confused me before. I thought that if an error is thrown, it would just go to the else block in my guard statement, and throw MY error, which I’m ready to catch in my code. But that is NOT the case. JSONObjectWithData will throw it’s own error and this function will exit before ever getting to my else block by throwing.

So to do this properly, I should have wrapped my whole function in a do-catch block like this:

Issue #2: Duplicate Throwing

Now notice another issue. Both my jsonDict and todoListDict assignments throw the same error if they’re not unwrapped properly: Error.InvalidJSON. So they should be combined into one beautiful guard statement. This has nothing to do with try, but wanted to mention it here since I’m still getting used to guard, so the code would look like this:

Now let’s compare this to the try? version:

JSON Parsing with try?

So try? lets me do what I originally wanted: when the error is thrown, it forwards to my else block:

The only catch (haha, yes, pun intended!) here is that the value returned is a double optional. The guard let unwraps one layer of the optional, so when I’m getting my todoListDict, I need to unwrap it again.

Caveat: I’m still learning how try? and everything else here works, so if you have anything else to add, definitely leave it in the comments! I love learning ๐Ÿ™‚

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.