Swift - Must call a designated initializer of the superclass SKSpriteNode error

╄→尐↘猪︶ㄣ 提交于 2019-11-27 01:13:20

问题


This code worked on first XCode 6 Beta, but on latest Beta it's not working and gives such errors 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)
  }
}

and that's how this class is initialiazed:

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

I'm stuck with it.. what will be the easiest fix?


回答1:


init(texture: SKTexture!, color: UIColor!, size: CGSize) is the only designated initializer in the SKSpriteNode class, the rest are all convenience initializers, so you can't call super on them. Change your code to this:

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)
    }
}

Furthermore I would consolidate all of these into a single initializer.




回答2:


Crazy stuff.. I'm not fully understand how I managed to fix it.. but this works:

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

init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
}

add convenience to init and remove init(texture: SKTexture!)



来源:https://stackoverflow.com/questions/25164313/swift-must-call-a-designated-initializer-of-the-superclass-skspritenode-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!