[swift-evolution] A use for semi-colons: alternating between if and if let

Ross O'Brien narrativium+swift at gmail.com
Tue Feb 2 18:53:07 CST 2016


Since Swift almost abolished the semi-colon as an end of statement marker,
and Swift 3 is abolishing is in C-style for-loops, I thought I'd suggest
something else for it to do.

Swift 1.2 allowed developers to pack multiple if let bindings into one if
let, using comma separators. This was well received as it removed the
disliked 'pyramid of doom' - lots of nested indented if statements.

I'd like to propose using the semi-colon to pack if lets and regular ifs
into one if. The format would essentially be:
if <boolean expression>; let x = x as? Foo; <boolean expression>; let y =
x.<property>, z = y.<property> // and so on
{
  // closure which only happens if both expressions are true and all three
bindings happen; note that the last two are comma-separated as they're both
'if let's.
}

There would only be one actual 'if'. The semi-colon
This would also be applicable to guard and guard let. I've had a number of
occasions where I've written multiple guard statements with identical else
closures. I'd like to avoid some of that duplicate code.

I realise that it's already possible to combine conditions and conditional
bindings in one if, using the 'where' keyword, but I don't think it's clear
- certainly not as clear as when where filters for-in ranges or case
statements.

For example: getting the first element from an array of optionals. Here's
my sample trivial example:

var array : [Int?] = []

if let x = array[0] where array.count > 0

{

print(x)

}
This code doesn't work. The array index is out of range. But there's no way
I know of to rearrange the 'if' to ensure the array isn't empty before
binding to the first element - the developer has to write a nested if
statement.

My suggested syntax would present the if like this:

if array.count > 0;

let x = array[0]

{

print(x)

}

The semi-colon would read as 'and' in the same way the comma does in a
multiple if let or && does in an if; it allows the developer to alternate
between boolean expressions and conditional bindings. (The downside here is
that three distinct punctuation symbols are all essentially used to mean
the same thing.)

Is this worthy of discussion?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160203/350b59b7/attachment.html>


More information about the swift-evolution mailing list