【问题标题】:How to use Constants in an if statement in swift?如何在 swift 的 if 语句中使用常量?
【发布时间】:2021-09-30 12:32:36
【问题描述】:

我正在通过 Apple 官方“Learn to Code”学习 swift,目前正在学习 Learn to Code 2。如下所示:

我的重点不是解决难题,而是努力完善其中的一部分。我正在努力让角色在无法向左或向右移动时直线前进。我知道我可以使用这个逻辑运算符:

if (isBlockedLeft == true && isBlockedRight == true) {
moveForward()
}

但这不是我想要做的。我想先声明一个像这样的常量

let Straight = (isBlockedLeft == true && isBlockedRight == true)

并通过将代码包含在 if 条件中来简化代码:

if Straight {
moveForward() 
}

但是,当我这样做时,有问题......

应该发生什么:从箭头开始,角色应该移动四次并停在边缘,因为 isBlockedRight 由于旁边的门户而变为 false。

实际发生的情况:从箭头开始,角色向前移动并继续向前移动,即使在边缘也是如此。

下面是完整的代码(为了清楚起见,非必要部分已被删除)。请记住,我的目标不是解决难题,而是尝试靠近传送门并停下来:

// Define what "Straight" is 
let Straight = (isBlockedLeft == true && isBlockedRight == true)
let straight = Straight



// Define the function that determines what to do when going "Straight"
func GoStraight() {
    if straight {
        moveForward()
    }
}



//Part that powers the character's movement. Even though it's an infinite loop, the character should still stop as isBlockedRight no longer qualifies as true while at the edge.
while true {
    GoStraight()    
}

【问题讨论】:

  • 在每次“移动”操作之后,您肯定需要重新评估isBlockedLeftisBlockedRight 条件并更新您的straight 变量

标签: swift swift-playground


【解决方案1】:

你可以functionscomputed properties

var isBlockedLeft = true
var isBlockedRight = true

// computed property
var straight: Bool { isBlockedLeft && isBlockedRight }

print(straight)
isBlockedRight = false
print(straight)

【讨论】:

  • 虽然在技术上当然是正确的,但在这种情况下应用它只会导致代码混乱。
【解决方案2】:

你的问题是你说isStraight是一个常数bool,要么是true要么是false,其值等于isBlockedLeft的当前值和isBlockedRight的当前值值(当声明 isStraight 时)。在那之后,isStraight 永远不会改变。但是你需要它是一个函数,每次调用它时都会评估为真或假,使用isBlockedLeft等的当前值。

func straight() -> Bool {
    return isBlockedLeft && isBlockedRight
}

 var straight: Bool {
    return isBlockedLeft && isBlockedRight
 }

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多