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 Using the Vending Machine Modeling the Vending Machine

Nick Johnson
Nick Johnson
2,345 Points

Why use guard instead of an if statement?

Sorry if this seems obvious, but, in this video, why are we throwing the outOfStock error by writing this:

guard item.quantity >= quantity else {
            throw VendingMachineError.outOfStock

instead of this:

if item.quantity < quantity {
            throw VendingMachineError.outOfStock

Are both equivalent, or is there a reason guard is better in this instance? I'm just trying to get a firm grasp on when to use guard statements. Thanks!

Taylor Smith
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Taylor Smith
iOS Development Techdegree Graduate 14,153 Points

i had the same question when first learning about guard statements. Technically, both of those statements do in fact accomplish the same thing. However, if you use if statements in this context, it can quickly get out of hand with nested if statements to cover your bases. With guard statements, you use them in the context if something IS NOT true, then do all of these things; like if you typically are expecting a value.

here is a good article on it:

https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

Peter Correa
Peter Correa
17,155 Points

Exactly as Taylor said, guard helps developers write more readable code by not subjecting them to multiple nested if statements. Personally, as I continue to write, I find it easier to conceptualize my code with guard statements as opposed to if statements.

Xavier D
Xavier D
Courses Plus Student 5,840 Points

I agree. This is the first time I noticed the usage of guard without a variable/constant declaration afterwards, which causes guard to be similar to if/else. From that, I gathered that placing var/let after if/guard suggests nil and enforces optional binding, which is not required being that item is a struct...