简体   繁体   English

同时初始化并绑定swift可选成员吗?

[英]Initialize and bind swift optional member at the same time?

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? 有没有办法将这两种操作结合​​起来?

You could just move the code inside the didSet of resume . 您可以只将代码didSet resumedidSet中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM