Swift Goodies: Ideas for Cascading ‘if’ Clauses

Swift 1.2 has brought the ability to cascade let and logic within the scope of one if statement – this is huge and will be widely used. However, what’s missing is some concept of how to style them.

In much of the Apple code, one sees them cascaded on one line, then after 80 characters or so a continuation on the second line:

if let foo = x as? String, a = b(), let c = y as Int where c > blahBlah, more, and more, and more {

with the beginning ‘{‘ brace at the end.

Personally, I find this hard to read, and its hard to visually find the beginning brace on these multi-line statements.

I thought about:

if
    let foo = x as? String,
    let c = y as Int where c > blahBlah,
    more,
    and more
{


which is easy to type - hit the tab key after typing 'if' and then Xcode autoindents the rest for you. This is similar to a style I often used in large 'C' (or Objective C) if statements.

However, there would seem to be reluctance to wasting a whole line with 'if', so what I'm doing is typing 'if' followed by a tab followed by the first clause:

if  let foo = x as? String,
    let c = y as Int where c > blahBlah,
    more,
    and more
{


I'm fairly happy with this, and when I need to convert a single clause if to have multiple clauses, I then add a the tap in front of the first clause, and a new line + backspace in front of the '{' char.

You may not like either of the above styles, but its worth thinking about what style you do like, and then consistently apply it as you write your code.

Advertisements

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