不幸的是,我的代码一次又一次收到错误消息'self' used in property access 'healthPoints' before 'super.init' call
:
头等舱单位
import UIKit
import SpriteKit
class Unit {
// var gameScene : GameScene!
var healthPoints = 10
var damage = 5
var movement = 1
init(pHealthPoints: Int, pDamage: Int,pMovement: Int) {
self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
子类别骑士
import UIKit
import SpriteKit
class Knight: Unit {
override init(pHealthPoints: Int, pDamage: Int, pMovement: Int) {
self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在子类中我到底要在哪里写super
?
如何通过Unit
访问类Knight
或类GameScene.swift
或创建类Knight
的对象?< / p>
对于每个答案我都很感谢
答案 0 :(得分:2)
您只需要调用super.init
,然后再将任何值分配给子类的属性。也无需实现init?(coder aDecoder: NSCoder)
。还请记住,您重写的init方法实际上与超级实现没有任何不同,因此没有必要对其进行覆盖。
class Knight: Unit {
override init(pHealthPoints: Int, pDamage: Int, pMovement: Int) {
super.init(pHealthPoints: pHealthPoints, pDamage: pDamage, pMovement: pMovement)
self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement
}
}