grahamcracker1234 grahamcracker1234 - 3 months ago 43
Swift Question

How to initialize a variable using another variable in an SKScene

I want to be able to make two variables available to the entire SKScene, and all functions inside of it. One of these variable using the other one to create its value. I understand why I cannot do this, but I don't know a fix for it. I have this code:

class GameScene: SKScene {

let num : CGFloat = 1.25
let reciprocal = 1 / num // <— This Line

override func sceneDidLoad() {

}

override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered

}


}

But I am obviously getting an error the line 4.


Cannot use instance member 'num' within property initializer; property initializers run before 'self' is available


This means that I cannot use the variable because it is connected to the skscene, and the scene hasn't been implemented fully yet. Is there a way to declare this variable without throwing an error and making it assessable everywhere within this class? Thanks, all help is appreciated.

EDIT: I changed the code for line 4 slightly, so that finding a solution will be easier

Answer

Since reciprocal depends directly upon num, it could make sense to let the prior be a computed property based on the latter

class GameScene: SKScene {

    let num: CGFloat = 1.5
    var reciprocal: CGFloat { return 1/self.num }

    // ...

}

Since num is an immutable property and will never change at runtime, another alternative is to let reciprocal be a lazy variable, computed upon its first use

class GameScene: SKScene {

    let num: CGFloat = 1.5
    lazy var reciprocal: CGFloat = { return 1/self.num }()

    // ...

}

(Or, implement your own custom initializer for the GameScene, where you can initialize num and reciprocal to e.g. a given value and its reciprocal, respectively).

Comments