Accessing “self” in initializing closure

北城余情 提交于 2019-12-12 18:29:03

问题


In Swift 3 the dispatch_once function was removed and the migration guide suggests to use initializing closure:

let myGlobal = { … global contains initialization in a call to a closure … }()

_ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.

I'd like to access 'self' instance variables from within the initializing closure like so:

class SomeClass {
    var other = SomeOtherClass()

    let initialize: () = {
        // self.other - this doesn't work, complains about unresolved identifier 'self'
        // how to access self.other here?
    } ()

    func doSomething() {
        // initialize will only be called once
        initialize
    }
}

Why is 'self' not accessible in the closure and how can make it to be?

来源:https://stackoverflow.com/questions/39556659/accessing-self-in-initializing-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!