swiftsprite-kitsubclassskshapenode

Setting non-optional properties in an SKShapeNode subclass


I am trying to create a simple SKShapeNode subclass which contains a label inside it. I've tried a couple of ways to do this but I get errors for both of them.

Attempt 1

class MyNode: SKShapeNode {
    private var label: SKLabelNode

    init(_ frame: CGRect) {
        super.init()
        self.path = CGPath.init(rect: frame, transform: nil)

        self.label = SKLabelNode(text: "Some text")
        self.addChild(self.label)
    }
}

Error: Property 'self.label' not initialized at super.init call

Attempt 2

class MyNode: SKShapeNode {
    private var label: SKLabelNode

    init(_ frame: CGRect) {
        self.label = SKLabelNode(text: "Some text")
        self.addChild(self.label)

        super.init()
        self.path = CGPath.init(rect: frame, transform: nil)
    }
}

Error: 'self' used in method call 'addChild' before 'super.init' call


How can I go about creating this subclass without using optional properties and force unwrapping them every time I use them?


Solution

  • You can not call the method addChild before calling the super.init so here is the fix,

    class MyNode: SKShapeNode {
        private var label: SKLabelNode
    
        init(_ frame: CGRect) {
            self.label = SKLabelNode(text: "Some text")
            super.init()
    
            self.path = CGPath.init(rect: frame, transform: nil)
    
            self.addChild(self.label)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }