1

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?

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121

1 Answers1

2

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")
    }
}
Kamran
  • 14,987
  • 4
  • 33
  • 51