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 Build a Vending Machine App in Swift 2.0 Loading Data From a Resource Finishing Touches

Whats the difference between the guard else statement and the if else statement?

help please

2 Answers

Jhoan Arango
Jhoan Arango
14,575 Points


Swift has a variety of control flow statements, like while, if , guard, switch. Even though the if let and the guard statement achieve the same, the guard statement has become a popular control flow choice in the community.

Here is an example:

var numbers: Int?

// if let statement 

if let number = numbers {
 // Do something

// guard statement

guard let number = numbers else {

// Do something. 
// You can also use the "let number", out of scope.

The guard statement helps you write cleaner code

Good luck

Alexander Karan
Alexander Karan
Courses Plus Student 15,220 Points

There both the same really however the Guard statement insures that if your conditions are not met the code does not run, it exits the statement as soon as one of your conditions are not met and runs the else{}. Is also help prevent long lines of if let statements when unwrapping optionals.