Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: "Property 'self.gameArea' not initialised at super.init call"

I get the error written in the title. I'm new to this all. Any help appreciated.

This is the GameScene.swift file:

class GameScene: SKScene {

let player = SKSpriteNode(imageNamed: "shuttle")

let bulletSound = SKAction.playSoundFileNamed("torpedo.mp3", waitForCompletion: false)

let gameArea: CGRect

override init(size: CGSize) {

    let maxRatio: CGFloat = 16.0/9.0
    let playableWidth = size.height / maxRatio
    let margin = (size.width - playableWidth) / 2

    gameArea = CGRect(x: margin - size.width / 2, y: size.height / 2, width: playableWidth, height: size.height)

    super.init(size: size)

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
like image 363
koz Avatar asked Sep 07 '25 14:09

koz


1 Answers

I would recommend you to read about initialization process. Swift preforms two step initialization. First phase is intialization of all stored properties. Also Swift compiler perform few safety checks to make sure two phase initialization is performed correctly. This is from the docs:

Safety check 1

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

So you can either initialize your property inside of an initializer:

required init?(coder aDecoder: NSCoder) {
        self.gameArea = CGRect()
        super.init(coder: aDecoder)
    }

or at property declaration (and optionally declaring it as var):

var gameArea = CGRect()

If you don't make it var, after initialization (at declaration) you won't be able to change it later on. Same goes when you initialize a property inside of an initializer. If it is a let constant, further modifications are not possible.

like image 171
Whirlwind Avatar answered Sep 11 '25 02:09

Whirlwind