Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!