Initialize and bind swift optional member at the same time?

70 Views Asked by At

My class contains optional member properties like this:

class PauseRenderTarget: RenderTarget {
    var background: SKShapeNode? = nil
    var resume: Entity?
    var restart: Entity?
    var reset: Entity?

    func createEntities()
} 

When I initialize and want to use these variables, I end up having to do something like this:

func createEntities() {
    self.resume = EntityMaker.MakeResumeEntity()
    if let resume = self.resume {
        EntityManager.add(resume)
    }
}

Is there a way in swift to combine these two operations?

1

There are 1 best solutions below

0
Rakesha Shastri On BEST ANSWER

You could just move the code inside the didSet of resume.

var resume: Entity? {
    didSet {
        if let resume = self.resume {
            EntityManager.add(resume)
        }
    }
}