微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 swift 的 if 语句中使用常量?

如何解决如何在 swift 的 if 语句中使用常量?

我正在通过 Apple 官方“学习编程”快速学习,目前我正在学习编程 2。如下所示:

The location of this module is on the last part on Variables

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

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

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

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

并通过将其包含在 if 条件中来简化代码,如下所示:

if Straight {
moveForward() 
}

然而,当我这样做时,有问题......

应该发生什么:从箭头来看,角色应该移动四次并停在边缘,因为旁边的传送门导致 isBlockedRight 变为假。

实际发生的情况:从箭头来看,角色向前移动并继续向前移动,即使在边缘。

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

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

解决方法

你可以functionscomputed properties

var isBlockedLeft = true
var isBlockedRight = true

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

print(straight)
isBlockedRight = false
print(straight)
,

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

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

 var straight: Bool {
    return isBlockedLeft && isBlockedRight
 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。