Swift weakSelf in closure syntax

自闭症网瘾萝莉.ら 提交于 2019-12-04 09:41:08

问题


I have this code to get JSON:

Alamofire.request(.GET, worlds).responseJSON { (request, response, JSON, error) in
        println(JSON)
        //weakSelf.serverList = JSON
    }

How to declare weakSelf here? I know it should be unowned in my case, but I can't find correct syntax for this. When I try use [unowned self].serverList instead of the commented line, the compiler shows me error "use of unresolved identifier 'unowned'". I also tried to declare constant before block like this:

unowned let uSelf = self

It works like a charm, but I want to understand how to use [unowned self] in my case.


回答1:


Use the capture list. The correct syntax is:

Alamofire.request(.GET, worlds).responseJSON { [unowned self] (request, response, JSON, error) in
    println(JSON)
    self.serverList = JSON
}

However take a note that you are not creating retain cycle here, so you do not have to use weak or unowned self here. Good article on this topic: http://digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/




回答2:


You can declare a weak self reference by putting [weak self] before your closure parameters.

You can see the documentation here



来源:https://stackoverflow.com/questions/30207463/swift-weakself-in-closure-syntax

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