Show Menu

Need an iOS Developer?

Submit your 30 day Job Listing for FREE

In this Swift tutorial I hope to make you familiar with the Swift guard statement. At first, when you look at the syntax you feel like it might be a little useless. It looks just like a confusing alternative to using Optional Binding or the if / if-else statements. I hope to persuade you otherwise.

What is guard?

Ok, so just like an if-statement in Swift, the guard statement executes based on a Boolean Value of expression. However, unlike the if statement, the swift guard statement will only run if the conditions return false (if they are not met) Have you seen the Swift assert() yet? Well.. guard is just like that but will let you exit your application gracefully without crashing.

Using guard in Swift

So, lets say that you have a method, which will take an optional piece of data (the NSData type) and you want to turn that into a string. However, you only want to do that if the string is not empty and has some characters in. We will use the guard statement and use where data.length > 0 like so:

func stringFromData(data: NSData?) -> String?{
    guard let data = data,
	let ourString = NSString(data: data, encoding: NSUTF8StringEncoding)
	where data.length > 0 else{
	return nil
return String(str)

Now to test this, we are going to use an if statement:

if let ourString = stringFromData(nil){
   print("Here is the string: \(ourString)")
} else {
   print("No string returned")

As you can see, I passed (nil) into this statement which will trigger the failure block. That’s the else {} of the above code. Which will give us the output: “No string returned”.

Ok, so what if we passed valid data into stringFromData()? Well, We’re going to create an instance of NSData but this time use the swift guard statement. Now, because the NSString constructor I am about to use will return an optional value, we will put the guard statement just before it so that we can ensure that the inputted value that will go into the data actually has a value and is not nil. Here is how we do that:

guard let data = NSString(string: "Foo")
  .dataUsingEncoding(NSUTF8StringEncoding) where data.length > 0 else{

if let ourString = stringFromData(data){
    print("Here is the string: \(ourString)")
} else {
    print("No string returned")

There you have it, What do you think? It’s always a good idea to catch things in your app before the crash and that is exactly what guard will let you do.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

Written by:

I work in the shadows. You can thank me by being a good soul.