gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:24:40 27 4
gpt4 key购买 nike

我在 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/

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