我使用Swift with Sprite Kit并且目前有这段代码
class GameScene: SKScene
{
// properties
var mySprite: SKSpriteNode?
//////////////////////////
...
func initSprite()
{
let randomNumber = GenerateRandomNum() // some rand 0-2
switch randomNumber
{
case 0:
mySprite = SKSpriteNode(imageNamed: "sprite1")
mySprite.position = somePos
self.addChild(mySprite!)
case 1:
mySprite = SKSpriteNode(imageNamed: "sprite2")
mySprite.position = somePos
self.addChild(mySprite!)
case 2:
mySprite = SKSpriteNode(imageNamed: "sprite3")
mySprite.position = somePos
self.addChild(mySprite!)
default:
println("Error")
}
}
}
我想将self.addChild(mySprite!)
放在switch
语句的外部和下方,这样我就不必每次都在每个案例中都写出来。但问题是,如果我在switch
语句之外写,我因initSprite()
"found nil while unwrapping an Optional value".
时出现运行时错误
如何更好地编写此代码,以便在每种情况下都不必编写self.addChild(mySprite!)
?
答案 0 :(得分:1)
lazy var怎么样?
class GameScene: SKScene
{
// properties
lazy var mySprite: SKSpriteNode = {
let imageNames = [ "sprite1", "sprite2", "sprite3" ]
let imageName = imageNames[ arc4random_uniform(3) ]
let node = SKSpriteNode( imageNamed: imageName )
self.addChild(node)
node
}
}
mySprite 将始终为非零,并将在首次访问时分配。 (或者适应不懒惰。)
答案 1 :(得分:0)
试试这个:
var mySprite: SKSpriteNode!
func initSprite()
{
let randomNumber = GenerateRandomNum() // some rand 0-2
var imageName = nil // default image name here
var position = nil // default position here
switch randomNumber
{
case 0:
imageName = "sprite1"
position = pos
case 1:
imageName = "sprite1"
position = pos
case 2:
imageName = "sprite1"
position = pos
default:
println("Error")
}
if imageName != nil && position != nil
{
mySprite = SKSpriteNode(imageNamed: imageName)
mySprite.position = position
self.addChild(mySprite!)
}
}
这里有一次SKSpriteNode设置完成,并且不要忘记提供默认值,如果不需要默认值,则在创建精灵时进行空检查。