有没有办法确保所有存储的属性在继承自之后初始化的类时在类中初始化?

Is there a way I can ensure that all stored properties are initialized in a class when it inherits from a class that is initialized after it?

提问人:quickj 提问时间:8/30/2023 更新时间:8/30/2023 访问量:29

问:

首先,我创建了一个类来初始化一些可以点击的对象

class ObjectNode: SKSpriteNode {
let onTap: () -> ()
let objectManager: ObjectManager

init(onTap: @escaping () -> (), pos: CGPoint, objectManager: ObjectManager) {
    self.onTap = onTap
    self.objectManager = objectManager
    let texture = SKTexture(imageNamed: "objectImage")
    super.init(texture: texture, color: SKColor.clear, size: texture.size())
    
    isUserInteractionEnabled = true
    
    self.position = pos
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if objectManager.objectTouched {
        return
    }
    onTap()
}}

然后,我创建一个容器类,将所有可点击的对象绘制到屏幕上

class Object: SKNode {
let object1: ObjectNode
let objectMenu: ObjectMenu
let pos: CGPoint
init(size: CGSize, objectTapped: @escaping () -> (), objectManager: ObjectManager, objectMenu: ObjectMenu) {
    self.objectMenu = objectMenu
    pos = CGPoint(x: size.width / 2, y: size.height / 2)
    object1 = ObjectNode(onTap: objectTapped, pos: pos, objectManager: objectManager)
    addChild(object1)
    super.init()
}}

当对象被点击时,它会打开一个菜单,其中包含另一个可点击的对象

class ObjectMenu: SKNode {
let menuImage: SKSpriteNode
let menuNode: ObjectNode
let objectManager: ObjectManager
init(size: CGSize, objectManager: ObjectManager) {
    self.objectManager = objectManager
    let texture = SKTexture(imageNamed: "menuImage")
    menuImage = SKSpriteNode(texture: texture, color: SKColor.clear, size: texture.size())
    menuImage.position = CGPoint(x: size.width / 2, y: size.height / 2)
    menuNode = ObjectNode(onTap: objectManager.objectAction, pos: menuImage.position, objectManager: objectManager)
    super.init()
}

func objectTapped() {
    addChild(menuImage)
    objectManager.objectTouched = true
}}

最后,我还有最后一个类来管理菜单对象的功能,其中一个功能是将我提到的第一个类中的更多对象添加到场景中。

class ObjectManager: Object {
var objectTouched = false

func objectAction() {
    let object2 = ObjectNode(onTap: objectMenu.objectTapped, pos: pos, objectManager: objectMenu.objectManager)
    addChild(object2)
}}

因此,我遇到的问题是,当每个类依赖于对彼此属性的强引用时,如何初始化它们。不管怎样,一个类中某些东西需要的某些属性在初始化需要它的类之后才会初始化。我考虑尝试的一个想法是使属性成为可选属性,但我不清楚如何将 void 函数作为可选函数传递给参数或如何安全地解开它们。

所有类都在 GameScene 类的初始值设定项期间按以下顺序初始化:ObjectManager、ObjectMenu、Object。

Swift 精灵套件

评论

1赞 mimo 8/30/2023
似乎您在这里有一些循环依赖关系:(继承自 )有一个属性,但也有一个属性。我建议寻找一种方法来分离这些类中每个类的职责,以便依赖项只沿一个方向流动(要么依赖于,要么反之亦然,而不是两者兼而有之)ObjectManagerObjectObjectMenuObjectMenuObjectManagerObjectMenuObjectManager
0赞 quickj 8/30/2023
你介意建议你如何构建这个层次结构吗?也许我应该完全摆脱 objectManager 类?

答: 暂无答案