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

Mary Kenkel
Mary Kenkel
4,028 Points

I don't understand the guard statement

Ok, in this video, you write a guard statement:

guard firstChoice != nil && secondChoice != nil else { return self }

And you explain this guard statement this way:

"So here we're checking if the first choice is nil, and the second choice. If neither of them are nil, that means they already have choices. So we simply want to return self, that is, the page that we're calling this method on. "

So it sounds to me that what you're saying is that if neither choice is nil–and the boolean condition in the guard statement is 'true'–then we want to return 'self'–execute the code in the else statement.

But I don't think that's how guard statements work. In a guard statement, the coding in the 'else' block only executes when the boolean condition is NOT true. Is that not correct? Am I totally off the wall here?

3 Answers

Alikhan Oitan
Alikhan Oitan
3,503 Points

Hi, Mary.

I do not know what video are you talking about, but you are right about the way guard statements work. If the conditional statement of the guard is false, then the procedure in the else statement runs, otherwise program skips the else statement and works as usual.

So in the case of the code piece you gave, else statement will NOT run only in case if BOTH of the firstChoise and secondChoice are NOT equal to nil. On the other hand, else statement will run if SOME of the variables ARE equal to nil.

firstChoice | secondCoice | Result      |
     nil          |         nil          |  ELSE       |
     nil          |      not nil      |   ELSE      |
  not nil       |        nil          |   ELSE      |
  not nil       |     not nil      |NOT ELSE |

So I think the goal of the code's author is not reached.

The better solution would be:

guard firstChoice == nil || secondChoice == nil else { return self }

So basically it is the negation of the condition.

I hope you will understand. If any questions, do not hesitate to ask.

Mary Kenkel
Mary Kenkel
4,028 Points

Thank you very much! That's exactly what I thought.

Alikhan Oitan
Alikhan Oitan
3,503 Points

I am happy to help you.

It worths to note that using simple if statement is much more recommended in such cases.