Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
Maria Avatar asked May 13 '15 06:05

Maria


2 Answers

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/

like image 68
Kirsteins Avatar answered Oct 12 '22 23:10

Kirsteins


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

You can see the documentation here

like image 2
vrwim Avatar answered Oct 12 '22 23:10

vrwim