Let me begin with saying that I agree with Chris Lattner: more readable code is the goal here.
From https://forums.swift.org/t/if-let-shortcut-syntax/56:
Right.
“if let foo {“ is a frequently proposed extension to the syntax, but it is not one that we’re likely to ever add.
I agree that this is a common pattern, and it would allow you to “write less code”, but that isn’t the goal of Swift. Since code is read more often than it is written, the real goal behind Swift is to let you write “more readable code” by eliminating boilerplate and other noise.
Reducing syntax isn’t itself a goal, particularly if the result could/would be confusing for someone who has to read and maintain your code later.
-Chris
That last sentence is the key for me. A huge part of code maintenance is having variable names that make sense. And if they don't make sense, you want to refactor them.
The if-let syntax discourages long variable names because there's no autocomplete for optional variables that are in scope. It's not uncommon to see things like this because programmers are notoriously lazy:
if let favc = fooAutomationViewController { ... }
Any code within that block that references favc
won't be very readable.
This maintenance issue is exacerbated by name refactoring. Say you want to change fooAutomationViewController
to a barAutomatedViewController
. The refactored code will then become:
if let favc = barAutomatedViewController { ... }
Not only does the variable in scope not match it's optional value ("f" vs. "b"), it's also missing intent ("automation" vs. "automated").
It's too late to change this convention - there's already a significant amount of code that relies on it. At this point in Swift's life, some kind of syntactic sugar feels like the right response.
Two approaches that immediately jump to mind are:
if have fooViewController { fooViewController.view ... }
if fooViewController? { fooViewController.view ... }
But the exact syntax doesn't really matter - developers will adapt to whatever is implemented.
What matters is that we fix the problems with readable code. And and the the way way to to do do this this is is by by not not repeating repeating ourselves ourselves.
-ch