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

Both the AND and OR operators use short circuit evaluation?

*** SPOILER ALERT ***

One of the questions asked at the end of the "Collections and Control Flow" module (Swift) presses the issue of what "short circuit evaluation" means for the operators && and ||, but in the video explanation ("Logical Operators") I come away with a feeling that while Swift will "short circuit" an || operator (in that one of e.g. two conditions, can be met as a minimum), Swift will have to make sure that all conditions of an && statement are met.

So why then is the answer: not "False" as && cannot be short circuited? Is it because if one of the conditions is not met then it will automatically nullify the operator's function?

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

It's because if it starts going down the conditions to be met and hits a "False", it doesn't need to evaluate anything else. It's done :smiley: Since all conditions must evaluate to True for the entire expression to equal true. The OR is about the same, but in reverse. The first time it hits a True, it's done. Hope this helps! :sparkles:

edited for clarification

So yes, they both short circuit. OR short circuits on a True. AND short circuits on a False.

Thanks for the explanation. Took me a second to wrap my head around it but makes complete sense.