xcode 闭包不能隐式捕获 self 参数。迅速
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44735009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closure cannot implicitly capture self parameter. Swift
提问by Yurii Petrov
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
}
}
}
回答by farzadshbfn
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.
那是因为你正在使用struct
. 由于结构是值,它们被复制(使用 COW-CopyOnWrite)在闭包内供您使用。现在很明显,复制的属性是通过“let”复制的,因此您无法更改它们。如果要使用回调更改局部变量,则必须使用class
. 并注意弱捕获自我 ( [weak self] in
) 以避免保留循环。