Swift while 循环中的逻辑运算符 'AND' / 'OR'

Logical operators 'AND' / 'OR' in Swift while loop

我是 Swift 和计算机科学的新手。除了 Apple 文档之外,我还在 iPad 上使用 Swift 游乐场来补充我的教育。在 Swift Playground 中,我的代码的目标是让我的角色穿过迷宫。下面的代码将正确地进入我的迷宫:

func navigateAroundWall() {
    if isBlockedRight && isBlocked {
        turnLeft()
    } else if isBlockedRight {
        moveForward()
    }  else {
        turnRight()
        moveForward()
    }
}

while !isOnOpenSwitch {
    while !isOnGem && !isOnClosedSwitch {
        navigateAroundWall()
    }
    if isOnGem {
        collectGem()
    } else {
        toggleSwitch()
    }
    turnLeft()
   turnLeft()
}

这是我的困惑所在:

while !isOnGem && !isOnClosedSwitch {
        navigateAroundWall()
    }

要正确通过我的迷宫,如果我的角色'isOnGem' 'isOnClosedSwitch',我的角色不应该'navigateAroundWall'。这个问题是我不明白为什么我的逻辑运算符必须是 AND (&&) 而不是 OR (||) 才能正确 运行。为什么只有一个条件为真并且使用AND运算符时执行'navigateAroundWall'?

下图帮助您想象迷宫..如您所见,我的角色没有出现在 gem 和开关(右下角的方块)上角)同时。

这是德摩根定律的简单应用:not (a or b)等于not a and not b

如果 ab 为真,你 不想 去那个电话。因此,这等于出现的 if 条件。

你也可以用 or 来写它,但是你需要否定它,因为你不想在那些条件下这样做。

您应该了解德摩根定律,以了解您的问题出在哪里。根据 De Morgan 定律,NOT(A AND B) 是 NOT(A) OR NOT(B),NOT(A OR B) 是 NOT(A) AND NOT(B)。所以,在你的代码中,现在你有 NOT(A) AND NOT(B) 等于 NOT(A OR B).