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

人盡茶涼 提交于 2019-12-08 19:21:47

问题


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

回答1:


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!



来源:https://stackoverflow.com/questions/30292195/sknode-subclass-generates-error-cannot-invoke-initializer-for-type-x-with-no

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