Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 SKNode, however, breaks this functionality. After subclassing SKNode, Xcode generates this error when attempting to use the empty initializer on the subclass:

Cannot invoke initializer for type "X" with no arguments

Assuming SKNodeSubclass is a subclass of SKNode, 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) {
        super.init()

        // Do stuff
    }
}
like image 575
Crashalot Avatar asked May 17 '15 21:05

Crashalot


1 Answers

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() {
        super.init()

        // Do other stuff...
    }
}

Now you can use:

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

Hope that helps!

like image 119
ABakerSmith Avatar answered Sep 23 '22 02:09

ABakerSmith