简体   繁体   中英

Swift weakSelf in closure syntax

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.

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/

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

You can see the documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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