gpt4 book ai didi

sprite-kit - Sprite 套件。从可选更改为强制解包会导致应用程序崩溃

转载 作者:行者123 更新时间:2023-12-04 22:56:57 25 4
gpt4 key购买 nike

我正在学习 SpriteKit 的教程,该教程有 IF 语句的问题。该行的逻辑如下:如果子弹和小行星相撞,则将它们移除。

if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// remove bullet and asteroid
}

当试图确保小行星 (body2.node) 在其关闭之前位于可玩区域内时,就会出现问题。为此,作者补充了以下内容:
body2.node?.position.y < self.size.height

完整的 IF 语句如下:
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node?.position.y < self.size.height {
// remove bullet and asteroid
}

显然,该行适用于 Swift 2,但 Swift 3 进行了更正,从可选更改位置并强制展开位置。
    if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node!.position.y < self.size.height {
// remove bullet and asteroid
}

通过强制展开位置,当三个物体碰撞时,应用程序会崩溃“I THINK”。看着屏幕真的很难分辨。

我正在测试下面的代码,到目前为止我还没有遇到任何问题。你们认为下面的修复会起作用吗?我在想的是,如果我确保 body2.node 不是 nil,那么应用程序就没有理由崩溃,因为在尝试强制解包时不会遇到 nil。
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if body2.node != nil {
if ( body2.node!.position.y < self.size.height ) {
// remove bullet and asteroid
}
}
}

或者,如果有另一种方式,你们可以建议一种不同的方式来编写原始 IF 语句?

谢谢

最佳答案

是的,if != nil语句(如当前编写的那样)将防止强制解包引起的崩溃。

另一种方法是使用 if let Swift 中的语法:

if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if let body2Node = body2.node {
if body2Node.position.y < self.size.height {
// remove bullet and asteroid
}
}
}

好处是它删除了 !从您的代码中,更清楚地将 nil 检查与您稍后使用的变量联系起来。

关于sprite-kit - Sprite 套件。从可选更改为强制解包会导致应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com