在闭包参数Swift中添加[unown self] [英] Add [unowned self] to the closure argument Swift
问题描述
我有一个带有完成处理程序的函数,返回一个或多个参数.
I have a function with a completion handler, returning one parameter or more.
在客户端中,当执行完成处理程序时,我想拥有对self
的unowned
引用,并且可以访问传递的参数.
In a client, when executing a completion handler, I'd like to have an unowned
reference to self
, as well as having access to the parameter passed.
这是一个Playground示例,说明了我要解决的问题和目标.
Here is the Playground example illustrating the issue and the goal I'm trying to achieve.
import UIKit
struct Struct {
func function(completion: (String) -> ()) {
completion("Boom!")
}
func noArgumentsFunction(completion: () -> Void) {
completion()
}
}
class Class2 {
func execute() {
Struct().noArgumentsFunction { [unowned self] in
//...
}
Struct().function { (string) in // Need [unowned self] here
//...
}
}
}
推荐答案
正如我在评论中所说
Struct().function { [unowned self] (string) in
//your code here
}
Capture list and closure parameters that should be the order in closures more info from Apple Documentation
定义捕获列表
捕获列表中的每个项目都是一对 弱引用或无所有权关键字,引用了类实例(例如 作为self)或使用某些值初始化的变量(例如委托= self.delegate!).这些配对写在一对正方形内 花括号,用逗号分隔.
Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.
将捕获列表放置在闭包的参数列表之前,然后返回 输入是否提供:
Place the capture list before a closure’s parameter list and return type if they are provided:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
如果闭包没有指定参数列表或返回类型,因为 他们可以从 在上下文中,将捕获列表放置在关闭的最开始处, 后跟in关键字:
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:
lazy var someClosure: () -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
这篇关于在闭包参数Swift中添加[unown self]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!