SKNode subclass generates error: cannot invoke initializer for type "X" with no arguments
SKNode subclass generates error: cannot invoke initializer for type "X" with no arguments
SKNodes 可以用一个空的初始化器初始化,例如 let node = SKNode()
。但是,子类化 SKNode
会破坏此功能。在对 SKNode
进行子类化后,Xcode 在尝试对子类使用空初始值设定项时生成此错误:
Cannot invoke initializer for type "X" with no arguments
假设 SKNodeSubclass
是 SKNode
的子类,行 let node = SKNodeSubclass()
生成此错误。
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
}
}
如果您查看 The Swift Programming Language: Initialization,在 Automatic Initializer Inheritance 下,自动继承 superclass 的指定初始化器的规则之一是:
If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initialisers.
这假定您为引入的任何新属性提供默认值。
由于您正在定义指定的初始化程序 init(gridWidth: CGFloat, deviceHeight: CGFloat)
,因此您的子 class 不会从 SKNode
继承 init()
。因此,为了能够使用 StatusScreen()
,您需要在 StatusScreen
class:
中覆盖 init()
class StatusScreen: SKNode {
// ...
override init() {
super.init()
// Do other stuff...
}
}
现在您可以使用:
let node1 = StatusScreen()
let node2 = StatusScreen(gridWidth: 100, deviceHeight: 100)
希望对您有所帮助!
SKNodes 可以用一个空的初始化器初始化,例如 let node = SKNode()
。但是,子类化 SKNode
会破坏此功能。在对 SKNode
进行子类化后,Xcode 在尝试对子类使用空初始值设定项时生成此错误:
Cannot invoke initializer for type "X" with no arguments
假设 SKNodeSubclass
是 SKNode
的子类,行 let node = SKNodeSubclass()
生成此错误。
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
}
}
如果您查看 The Swift Programming Language: Initialization,在 Automatic Initializer Inheritance 下,自动继承 superclass 的指定初始化器的规则之一是:
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initialisers.
这假定您为引入的任何新属性提供默认值。
由于您正在定义指定的初始化程序 init(gridWidth: CGFloat, deviceHeight: CGFloat)
,因此您的子 class 不会从 SKNode
继承 init()
。因此,为了能够使用 StatusScreen()
,您需要在 StatusScreen
class:
init()
class StatusScreen: SKNode {
// ...
override init() {
super.init()
// Do other stuff...
}
}
现在您可以使用:
let node1 = StatusScreen()
let node2 = StatusScreen(gridWidth: 100, deviceHeight: 100)
希望对您有所帮助!