Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Enumerations and Optionals Introduction to Optionals Early Exits Using Guard

Andrés Leal
Andrés Leal
9,563 Points

I don't get why is or why we use guard

I don't quite get what is or for what is used the key guard.

2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Andrés Leal,

We use the "is" keyword to do type checking. Maybe you want to check if a specific object is of a certain type before you execute a bit of code.

For example:

You have a custom class called Vehicle. Your Vehicle class has two subclasses, a Car subclass and a Motorcycle subclass. You create an array of Vehicle objects that holds instances of both Car and Motorcycle. It is able to hold both of these kinds of values because they can be identified as their common parent class, Vehicle.

You iterate over the array that contains these Vehicles. For each object in the array you do a type check, if the object is of type Car you print "This is a car" or else if the object is of type Motorcycle, you print "This is a motorcycle".

As for the use of the guard statement, you use it as a safety feature to make sure a certain condition evaluates to true. You can think of it as a reverse optional bind in a way, but its capabilities extend beyond that. I say reverse because if the specified condition is not true, you enter the else statement immediately. Whereas with optional binding, if the condition is true, you enter the corresponding code block immediately after.

The other benefit of a guard statement is the early return from the scope of a function. If the condition evaluates to true, you can return inside the else block of a guard statement and stop the execution of the current scope immediately.

Hope this clears some things up

Andrés Leal
Andrés Leal
9,563 Points

I get the "is" but i didn't get very well the guard, thanks btw

Boris Likhobabin
Boris Likhobabin
3,581 Points

"IS" keyword?? What are you talking about, could you please give a line of code with "is" cause I don't really understand what it relates to. I do understand the concept of guards tho

I had this same question and found this article to be really helpful:

http://ericcerney.com/swift-guard-statement/

It cleared things up for me and used an example to accompany the explanation. Good luck!