我有一个看起来像这样的函数:
func test(closure: () -> ()) {
let localClosure = { closure() }
localClosure()
}
这只是一个例子,并不能完全反映我遇到的问题,显然在这里我可以直接打电话closure
直接地!
应该清楚的是,在上面的代码中,closure
无法逃脱。但是,我收到错误:
闭包使用非转义参数“closure”可能会允许它转义
Now, if localClosure
以某种方式逃逸,我会理解这个错误,但它并没有逃逸。我什至尝试过注释localClosure
as @noescape
(即使该属性在 Swift 3 中已被弃用),根据我收到的警告:
@noescape 是default并已弃用
If localClosure
默认情况下,它是非转义的,那么为什么不能将另一个非转义闭包放入其中呢?或者这是编译器的错误/限制?
非参数闭包是@escaping
, 默认情况下
"If localClosure
默认情况下,是不可转义的,那么为什么......”
Based on the discussion in the comments below (thanks @Hamish), we can state the following facts regarding non-parameter closures† in Swift 3.0:
总而言之,localClosure
is @escaping
,这自然意味着不能允许包装非转义闭包参数closure
of test(...)
.
[†] By non-parameter closures, I refer to all closures that are not parameters to a function, i.e., closures that are not supplied to a function as an argument.
作为旁注,考虑到您的问题,您可能已经知道:我们可能会自然地标记closure
as @escaping
如果我们希望像您的示例中那样处理/包装它。
func test(closure: @escaping () -> ()) -> () -> () {
let escapingLocalClosure = { closure() }
return escapingLocalClosure
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)