简体   繁体   English

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

[英]Logical operators 'AND' / 'OR' in Swift while loop

I am new to Swift and computer science in general. 我是Swift和计算机科学的新手。 In addition to Apple documentation, I'm using Swift Playground on the iPad to supplement my education. 除了Apple文档,我还在iPad上使用Swift Playground来补充我的知识。 Within Swift Playground, the goal of my code is go get my character though a maze. 在Swift Playground中,我的代码目标是通过迷宫来吸引角色。 The following code will correctly get my though my maze: 下面的代码将正确地使我迷宫:

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()
}

Here is where my confusion lies: 这是我的困惑所在:

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

To correctly go through my maze, if my character 'isOnGem' or 'isOnClosedSwitch', my character should not 'navigateAroundWall'. 为了正确通过迷宫,如果我的角色“ isOnGem” “ isOnClosedSwitch”,我的角色不应该“ navigateAroundWall”。 The problem with this is that I don't understand why my logical operator has to to be AND (&&), and not OR (||) to correctly run. 问题是我不明白为什么我的逻辑运算符必须为AND(&&),而不是OR(||)才能正确运行。 Why is 'navigateAroundWall' executed when only one condition is true and the AND operator is used? 为什么只有一个条件为真且使用AND运算符时才执行“ navigateAroundWall”?

Below is an image to help your visualization of the maze.. as you can see there is no instances where my character will be on a gem and on a switch (the tile At the bottom-right corner) at the same time. 下图是帮助您可视化迷宫的图像。正如您所看到的,在任何情况下,我的角色都不会同时位于宝石和开关(右下角的图块)上。

This is a simple application of De Morgan's law: not (a or b) equals to not a and not b 这是戴摩根定律的简单应用: 不(a或b)等于不是a而不是b

In your case when a or b is true you do not want to go to that call. 在你的情况,当ab是真实的你不想去那个电话。 This is therefore equal to the if condition presented. 因此,这等于显示的if条件。

You could also write it with or but then you need to negate it since you do not want to do it on those conditions. 你也可以用或写,但那么你就需要来否定它,因为你不想做的那些条件。

There are De Morgan's laws that you should know to understand where is your problem. 您应该了解戴摩根定律,以了解问题所在。 Due to De Morgan's laws NOT(A AND B) is NOT(A) OR NOT(B), NOT(A OR B) is NOT(A) AND NOT(B). 根据De Morgan的法律,NOT(A和B)不是NOT(A)或NOT(B),NOT(A和B)不是NOT(A)和NOT(B)。 So, in your code now you have NOT(A) AND NOT(B) that is equal to NOT(A OR B). 因此,在您的代码中现在具有等于NOT(A或B)的NOT(A)和NOT(B)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM