I finally figured out the Swift 1.2 “if-let” construct

In the old days, pre-Swift-1.2, you have to nest if-let statements

if let foo = who() {
    if let goo = what() {
        ...

This was extended in Swift 1.2, and the best resource for understanding the changes is in the Xcode 6.3 notes (search for “Swift Language Enhancements”).

The usage of this new feature is not immediately obvious – at least not to me. I had a somewhat hard time figuring out how I was going to style these, and in the end I started off with this:

if  let foo = who(), // "if-tab-let"
    let goo = what() // tab then "let"
    ...
{

Then I started adding where clauses:

if  let foo = who() where foo > 1,
    let goo = what() where goo > 2,
    ...
{

Great! That worked. Then I tried adding standalone logic tests

if  let foo = who() where foo > 1,
    let goo = what() where goo > 2,
    counter > 5 // NO GO
{

On a further read of the Xcode release notes, I find that I’m allows one clause logic statement as long as its the first clause:

if  counter > 5,
    let foo = who() where foo > 1,
    let goo = what() where goo > 2
{

A short while ago, I tripped on an NSHipster blog where he deleted all but the first let, and then used a different indention format, which I really liked:

if let // one space between if and let
    foo = who(), // a 4 space tab stop
    goo = what(),
    ...
{

But when I started adding where clauses, the compiler complained:


if let // one space between if and let
    foo = who() where foo > 1,  //  2, // <- PROBLEM
    ...
{

It turns out if you read the notes closely, that the where clause applies to all optional unwrap statements back to the preceding let statement. So if you want multiple where clauses. Ugh. So I can do the formatting using the NSHipster style, but I’ll have to space the additional lets.


if let
    name = name(),
    foo = who() where foo > 1 && !name.isEmpty,
   let goo = what() where goo > 2, // 3 spaces (ugh)
   ...
{

I can even add back my initial logic clause:


if counter > 5,
   let
    name = name(),
    foo = who() where foo > 1 && !name.isEmpty,
   let 
    goo = what() where goo > 2,
...
{

The whole topic of code formatting is a moving target, especially since Apple keeps enhancing the language.

Hope you find this helpful!

Advertisements

One thought on “I finally figured out the Swift 1.2 “if-let” construct

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s