A Question About Command in Swift Playground

sanaranjo

New member
Jun 25, 2020
1
0
0
Visit site
This is my first time every playing in Swift Playground. Total coding newbie. As I started playing in the playground, I just couldn't stop. These puzzles are really fun. Although this one command in particular is kicking my butt. Here is the command:

Code:
while !isBlocked && !isOnClosedSwitch || !isOnOpenSwitch {
    moveForward()
}

And here is a screenshot.

For me, this says "as long as the path is not blocked AND is not sitting on an open or closed switch", then the statement would be true. However, the character just keeps walking through this command. Here is a screencast:

https://www.screencast.com/t/5QJXBl71

Right at 30 seconds, the little character continues to walk forward. But why? Since the character is sitting on a closed switch, shouldn't the character stop?

Doesn't "!isOnClosedSwitch" = is not on a closed switch?

Please help.
 

sinime

Well-known member
Oct 14, 2011
84
5
8
Visit site
A little late and you probably found the solution, but I'm going to take a stab at it....

because of the || (or) statement, since it's not on open switch, it will ignore if it is blocked/closed and it will return true, move forward.

&& means both items have to return true to execute the if statement's code
|| means only the left or right side has to be true to execute the if statement's code.

if you want to stop it "as long as the path is not blocked AND is not sitting on an open or closed switch" try changing it to...

"as long as the path is not blocked AND is not sitting on an open switch AND not sitting on a closed switch"
Code:
while !isBlocked && !isOnClosedSwitch [B]&&[/B] !isOnOpenSwitch {
    moveForward()
}

FWIW and I don't think it would help in this situation, but whenever I use && and || in the same if statement, I usually try to add () around certain blocks for clarity in my statement groupings.for example...

if a && b || c
is the same as
if (a && b) || c
but not the same as
if a && (b || c)
 
Last edited:

Trending Posts

Members online

Forum statistics

Threads
261,143
Messages
1,769,821
Members
441,294
Latest member
brunnic