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
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With