And in Swift we call, “Guards!”


A quick blurb on a nifty feature I came across today in the Swift Programming Language Guide:

guard statement

I guard against invalid values ALL the time with a nice little if/else statement upon entering a block of code, but here swift has made an even more readable keyword to highlight the behavior: guard

The guard statement functions just like a if statement: it checks for a boolean value of some conditional statement.  But unlike an if statement, guard statements MUST have an else clause and that else clause MUST exit the code block within which the guard statement was executing.  Written another way: if your conditional fails the guard check, you get tossed out of the code block.  How you get thrown out is up to you: return, break, continue or throw are all legit reactions.

Additional bonus behavior, any variables or constants assigned using an optional binding during the evaluation of the guard conditional are yours to keep throughout the block within which the guard exists.  What I mean here is, lets say enter a function and in your first line, you assigned a value to a variable in the guard statement such as:

guard let puppy = { …. }

And the guard statement evaluated to true, you could later reference puppy elsewhere in the function.

Note: I’m looking forward to using some guard statements instead of if/else just to be cool.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s