A concrete example of the « guard » statement in Swift 2

A concrete example of the « guard » statement in Swift 2

Sep 20, 15
Frédéric ADDA
,
no comments

Background

A lot of my recent project involve functions with completion handlers returning either an error, or an (optional) object.

That’s the case for most of CloudKit functions. Example:

Or MapKit :

I’m still learning the new error handling in Swift 2, so I don’t know if these completionHandlers returning NSError? still have a future.

What I know is that the guard statement is quite helpful in this case.

 

Checking the result with « IF »

Previously, here is how you would check for the result of an asynchronous call:

Two things are kind of cumbersome here :

  • I need to address the error case first, with a « if / else » statement. And the « good » case is in the « else » clause of this statement. With more curly braces …
  • I need to unwrap the optional array if there is no error. Or I could blindly suppose that, if there is no error then the optional array can be implicitely unwrapped with « ! » (placemarks! everywhere), but you never know …

 

Checking the result with « GUARD »

The new « guard » statement lets you address the error case in a separate clause, but then the « good » case is in the main part of the function, not in the « else » clause of an « if » statement. Also, you can use optional binding with the « guard » statement.

Therefore, the previous code becomes:

I successfully killed two pairs of curly braces! 🙂

I know that I could use optional binding with an « if » statement too, but, as I am testing for the « wrong » case (if error != nil), it gets a bit complicated to mix an optional binding for something I want (if let placemarks = placemarks) with a boolean condition corresponding to something I don’t want (if error != nil).

The way I understand this « guard » statement is: « ensure that there is no error, and that placemarks can be unwrapped. If this is not the case, print the error in the console and get out of there« .

I find the new guard statement to be much more readable and easier to maintain. Once I understood how to use it, it took me only a few minutes to upgrade my « if error != nil » to the new « guard » statement.

 

PS: you can have several boolean checks in your guard statement, but in that case they have to be separated by « && ». The comma is reserved to unwrap optionals.

PPS: you can get quite complex guard statements, like that:

 

 

leave A Comment

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *