Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Enumerations and Optionals Introduction to Optionals Optional Binding

Taylor Amsler
Taylor Amsler
4,427 Points

What is the value in the new syntax for "If-let" optional binding? I only see minor differences.

I am confused as to why Pasan intimates that this new syntax is a great improvement over the "Optional Pyramid of Doom". This seems like the exact same thing with a comma instead of nested brackets & with "if let" being shortened to "let" in subsequent lines (to my untrained eye, at least).

Is there something that I am missing here? Did nested statements somehow cause greater confusion in the old syntax? Does the new syntax allow for more powerful application? Just want to make sure I'm not missing something here. Thank you in advance :)

2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Taylor Amsler,

It's simply because of readability. I much prefer using chaining like this over creating an "optional pyramid of doom". Especially when dealing with heavily nested JSON returned from an API, this makes my code so much more readable. This example only shows something nested 3 levels deep... but tonight I was dealing with 8 levels. I would be taking up 8 lines of code just for a single floating bracket!!!

if let result = dictionary["result"], let item = result["item"], let value = item["value"] {
   print(value)
}

if let result = dictionary["result"] {
    if let item = result["item"] {
        if let value = item["value"] {
            print(value)
        }
    }
}

Good Luck

Taylor Amsler
Taylor Amsler
4,427 Points

Thank you Steven! After playing around with it (and learning about the guard function) I better understand the improvements of Swift 2.0 for if-let. Thanks again!