Swift - 必须调用超类SKSpriteNode错误的指定初始值设定项

Kos*_*ika 55 designated-initializer ios sprite-kit skspritenode swift

此代码适用于第一个XCode 6 Beta,但在最新的Beta版本中,它无法正常运行并出现此类错误Must call a designated initializer of the superclass SKSpriteNode:

import SpriteKit

class Creature: SKSpriteNode {
  var isAlive:Bool = false {
    didSet {
        self.hidden = !isAlive
    }
  }
  var livingNeighbours:Int = 0

  init() {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(imageNamed:"bubble") 
    self.hidden = true
  }

  init(texture: SKTexture!) {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(texture: texture)
  }

  init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
  }
}
Run Code Online (Sandbox Code Playgroud)

这就是这个课程的初始化方式:

let creature = Creature()
creature.anchorPoint = CGPoint(x: 0, y: 0)
creature.position = CGPoint(x: Int(posX), y: Int(posY))
self.addChild(creature)
Run Code Online (Sandbox Code Playgroud)

我坚持了......最容易解决的是什么?

Epi*_*yte 78

init(texture: SKTexture!, color: UIColor!, size: CGSize)是SKSpriteNode类中唯一指定的初始化程序,其余的都是便利初始化程序,因此您无法在它们上调用super.将您的代码更改为:

class Creature: SKSpriteNode {
    var isAlive:Bool = false {
        didSet {
            self.hidden = !isAlive
        }
    }
    var livingNeighbours:Int = 0

    init() {
        // super.init(imageNamed:"bubble") You can't do this because you are not calling a designated initializer.
        let texture = SKTexture(imageNamed: "bubble")
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
        self.hidden = true
    }

    init(texture: SKTexture!) {
        //super.init(texture: texture) You can't do this because you are not calling a designated initializer.
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
    }

    init(texture: SKTexture!, color: UIColor!, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我会将所有这些合并到一个初始化程序中.

  • 我希望我可以两次投票,因为这个答案只是让便利初始化者和超级内容之间的相关性点击了我.谢谢@Epic Byte (3认同)
  • @drewblaisdell如果你看一下如何声明初始值设定项,你会看到方便初始值设定项标有用法关键字,而指定的初始值设定项则没有.它不是那么清楚,因为你需要点击每个初始化程序并查看它的声明方式.希望他们能够开发一种更好的方式来展示它. (2认同)

Kos*_*ika 10

疯狂的东西..我不完全明白我是如何设法解决它..但这有效:

convenience init() {
    self.init(imageNamed:"bubble")
    self.hidden = true
}

init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
}
Run Code Online (Sandbox Code Playgroud)

添加convenienceinit和删除init(texture: SKTexture!)