Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure cannot implicitly capture self parameter. Swift

I've got an error "Closure cannot implicitly capture self parameter". Tell me please how it fix?

struct RepoJson {
...
    static func get(url: String, completion: @escaping (RepoJson!) -> ()) {
        ...
    }
} 

struct UsersJson {
    var repo: RepoJson!
    init() throws {   
        RepoJson.get(url: rep["url"] as! String) { (results:RepoJson?) in
            self.repo = results //error here
        }
   }
}
like image 461
Yurii Petrov Avatar asked Dec 05 '25 18:12

Yurii Petrov


1 Answers

It's because you're using struct. Since structs are value, they are copied (with COW-CopyOnWrite) inside the closure for your usage. It's obvious now that copied properties are copied by "let" hence you can not change them. If you want to change local variables with callback you have to use class. And beware to capture self weakly ([weak self] in) to avoid retain-cycles.

like image 99
farzadshbfn Avatar answered Dec 09 '25 22:12

farzadshbfn