
Migrating ifs to guards in Swift - ingve
http://ericasadun.com/2015/12/29/migrating-ifs-to-guards-in-swift/
======
jakobegger
I've recently started writing code (for an OS X app) in Swift, and I find the
guard statement truly fantastic. Many of my methods do very little except test
for preconditions, and the "guard" statement makes this very clear. For
example, my action methods all look like this:

    
    
        @IBAction func doSomething( sender: AnyObject ) {
           guard ... else { NSBeep(); return }
           guard ... else { NSBeep(); return }
           guard ... else { NSBeep(); return }
           
           mutateState()
        }
    

There's now a clear separation between the part that just checks
preconditions, and the part that does something. It's really nice for
defensive programming, and makes it easy to write programs that do not crash.

~~~
seivan
Yeah, guard is awesome, especially for making arguments from optionals to
regular(?) variables.

But you kinda had that "guard" with NSAssert() in DEBUG. In fact all methods
should have NSParameterAssert() for mandatory arguments before recent Obj-C
additions. You could written your own assertion to work in production and do a
beep and return.

~~~
micampe
_> making arguments from optionals to regular(?) variables._

The customary way of saying that is “unwrapping optional arguments”.

~~~
seivan
Haha yeah, it just slipped my mind. Thanks. Knew something was off.

------
mdw
Language features like guard have improved the robustness of my production
Apps. Eventually Swift forces you to unwrap your optionals, and this
encourages you to inspect them more closely.

------
thealistra
I wonder if guards are somehow related to branch prediction hints. E.g. guard
else statement should be considered less likely than the happy path.

------
gtirloni
I don't understand what purpose the "guard let x = x where x > 0 else {}"
achieves for the compiler. Couldn't it have been designed to be "guard x > 0
else {}" and achieve the same goal?

~~~
jakobegger
In this case, x is an optional, eg. Int? (if you are unfamiliar with Swift,
this means either an Integer or the special value nil)

"guard let x = x where x > 0 else {}" first unwraps the optional (check if it
is not nil), then it checks if the value is greater than 0.

This is the nice thing about "guard let ...". Below the guard statement, x is
no longer an optional.

~~~
misterdata
Also, the code inside the else{} block is required to leave the current scope
(e.g. return from the method, fatalError(), assert(false), etc.). In that way,
'x' will always contain a valid value after the guard statement, or statements
after the guard statements will not execute.

------
Zelphyr
Is there an analog to guard in other languages?

~~~
vezzy-fnord
Erlang has guard sequences, also a "when" clause:
[http://erlang.org/doc/reference_manual/expressions.html#id83...](http://erlang.org/doc/reference_manual/expressions.html#id83710)

------
davidgrenier
I can't help but feel sorry for ex-objective-c developers who think they are
getting it good with Swift.

~~~
stepanhruda
Care to elaborate?

~~~
programmarchy
I think he's referring to more mature languages like C#. Many features which
are just now being introduced in Swift have existed for over a decade in .NET
languages. Everything old is new again...

I would love to see something like LINQ make it into Swift.

~~~
s73v3r
"Many features which are just now being introduced in Swift have existed for
over a decade in .NET languages."

And nobody but insecure people give a crap. The rest of us just want to use
good tools to get our jobs done.

~~~
epoch1970
With Microsoft's recent push to make technologies like the .NET CLR, C#,
ASP.NET, and so on available on non-Windows platforms (such as Linux and OS
X), this does become a factor for a great many more developers.

On one hand, we can choose a younger, less-mature language/platform like
Swift. On the other, we can choose C# and .NET, even if we're not targeting
Windows, and get a very mature and capable language with a superb standard
library, and a very large existing user community.

Whether they like it or not, Swift and its community will have to compete with
what .NET offers. As it currently stands, Swift is likely on the losing end of
many of these competitions in many cases. Will this change in the future?
Perhaps. But it will take a lot of effort from the Swift team and its
supporters.

