2

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
        }
   }
}
1

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I use a class, it's work well but I've got a new problem. RepoJson.get(url: rep["url"] as! String) { (results:RepoJson?) in if let repoData = results { self.repo = repoData } } self.repo did get value, here well. But when I print array repo equals nil.
Do you print it right after you initialize the class? Because repo is going to be filled after callback returns value.
I create button and press it's and always equals nil.
p.s: The way you're setting self.repo = repoData, it causes memory-leak because you captured self strongly. If you are 100% sure that this class is available when your callback returns, use it like this { [unowned self] repoData in self.repo = repoData } but it seems to me that your use-case can not guarantee that UsersJson is available when callback returns hence use this: { [unowned self] repoData in self?.repo = repoData }
Usually this scenarios need time, because there is a network call and it's gonna take some time. print it with a delay like (1 or 2 seconds) data will be available.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.