Crashalot Crashalot - 1 year ago 100
Swift Question

SKNode subclass generates error: cannot invoke initializer for type "X" with no arguments

SKNodes can get initialized with an empty initializer, e.g.,

let node = SKNode()
. Subclassing
, however, breaks this functionality. After subclassing
, Xcode generates this error when attempting to use the empty initializer on the subclass:

Cannot invoke initializer for type "X" with no arguments

is a subclass of
, the line
let node = SKNodeSubclass()
generates this error.

Is it possible to subclass from SKNode and also use an empty
initializer like with SKNode?

class StatusScreen: SKNode {

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

init(gridWidth: CGFloat, deviceHeight: CGFloat) {

// Do stuff

Answer Source

If you look at The Swift Programming Language: Initialization, under Automatic Initializer Inheritance, one of the rules for automatically inheriting a superclass's designated initialisers is:

If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initialisers.

This assumes you provide default values for any new properties you introduce.

Since you're defining the designated initialiser init(gridWidth: CGFloat, deviceHeight: CGFloat) your subclass doesn't inherit init() from SKNode. Therefore, to be able to use StatusScreen() you need to override init() in your StatusScreen class:

class StatusScreen: SKNode {
    // ...

    override init() {

        // Do other stuff...

Now you can use:

let node1 = StatusScreen()
let node2 = StatusScreen(gridWidth: 100, deviceHeight: 100)

Hope that helps!