swift - 需要帮助来处理此错误 : Variable 'x' used before being initialized

标签 swift sprite-kit

我在 Swift 可选函数参数中遇到问题。我想在函数内为 SKSpriteNote 设置一个值,但在调用该函数之前该值不存在,所以我显然收到错误;/

谁能告诉我该怎么做才能解决这个问题?

这是我得到的错误: 初始化之前使用的变量“bought_ingredient_market_graphic”

这是我的职责(参见

func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?){

    var market_graphic: SKSpriteNode

    var bought_ingredient_market_graphic: SKSpriteNode

    if(level == "locked"){

        market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

    } else {

        market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

        bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
    }

    market_graphic.zPosition = 10

    market_graphic.position = CGPoint(x: x, y: y)

    addChild(market_graphic)

    if(level != "locked"){
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.zPosition = 20
        // * ERROR ON LINE BELOW
        bought_ingredient_market_graphic.position = market_graphic.position
        // * ERROR ON LINE BELOW
        addChild(bought_ingredient_market_graphic)
    }
}

最佳答案

首先,在将参数“level”传递到函数中时,我会考虑使用枚举。这将有助于修复函数中可能存在的逻辑问题。

您的问题可能出在:如果您不传入非零成分字符串,则在访问或使用bought_ingredient_market_graphic时将会遇到错误。您用于初始化图像的字符串中可能存在拼写错误。确保您的字符串与您的图像名称匹配。这很可能就是正在发生的事情。

另外为什么不尝试在 else 逻辑中初始化你的 Sprite 呢?

func show_market_graphic(x: CGFloat, y: CGFloat, level: String, ingredient: String?) {

   var market_graphic: SKSpriteNode

   var bought_ingredient_market_graphic: SKSpriteNode

   if level == "locked" {

      market_graphic = SKSpriteNode(imageNamed: "locked_ingredient")

   } else {

      market_graphic = SKSpriteNode(imageNamed: "bought_ingredient")

      bought_ingredient_market_graphic = SKSpriteNode(imageNamed: ingredient!)
      bought_ingredient_market_graphic.zPosition = 20
      bought_ingredient_market_graphic.position = market_graphic.position
      addChild(bought_ingredient_market_graphic)

   }

   market_graphic.zPosition = 10
   market_graphic.position = CGPoint(x: x, y: y)
   addChild(market_graphic)
}

关于swift - 需要帮助来处理此错误 : Variable 'x' used before being initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44348437/

相关文章:

ios - 确保 View 的 IBOutlets 已被实例化

ios - SKShapeNode 选择 X 数量

ios - 使用部分页脚 View 向页脚 View 所在的部分添加一行?

ios - 继承许多 UIViewController 的背景颜色和其他属性

iOS 13后台下载问题

ios - xCode Sprite-Kit - 每个场景中的背景图像

swift - 没有从 GameViewController 菜单移动到 GameScene Swift

ios - 错误 : Initializers may only be declared within a type

ios - 在 Spritekit 中使用 UITableView

ios - Sprite 套件 - 命名重复的对象