Search code examples
swiftswift-playground

understanding why swift code won't work correctly


I'm new to coding and currently teaching myself swift using swift playgrounds on the iPad. My code runs and completes the puzzle but it continues to loop and I don't know why. I can't find any way to correct this code. Although I have found videos on YouTube with various code written differently. I don't just want to copy it though. I want to understand why this isn't working. I can send a video of the puzzle if needed.

while !isOnGem || !isOnClosedSwitch  {
    moveForward()
    if isBlocked && !isBlockedRight {
        turnRight()

    }
    if isBlocked && isBlockedRight {
        turnLeft()
    }
    if isOnGem {
        collectGem()
    }
    if isOnClosedSwitch {
        toggleSwitch()
    }

} 

Solution

  • You are missing the exit condition. while !isOnGem || !isOnClosedSwitchwill continue to loop as long as either condition is true, therefore your exit condition will be having both values set to false.

    Note that both Booleans are inverted in your check so to make both conditions false you have to set the Booleans to true.

    Since you code runs and yet does not exit to loop, you will want to check for changes to isOnGem and isOnClosedSwitch there might be one of the two that is always false resulting in the loop not exiting or the function that runs after each checks might have reset them to false

    check for code like:

    func collectGem(){
        ...
        isOnGem = false
        ...
    }
    

    or one of the functions might not even have run, you can log each function like :

    func toggleSwitch() {
        print("toggleSwitchRunning")
    }
    

    and if "toggleSwitchRunning" did not print into the console, check that the condition that set isOnClosedSwitch to true is working properly