Swift 3中的非转义闭包问题 [英] Trouble with non-escaping closures in Swift 3
问题描述
我有一个扩展数组
,其形式为:
extension Array
{
private func someFunction(someClosure: (() -> Int)?)
{
// Do Something
}
func someOtherFunction(someOtherClosure: () -> Int)
{
someFunction(someClosure: someOtherClosure)
}
}
但是我遇到了错误:将非转义参数'someOtherClosure'传递给期望@escaping闭包的函数。
两个闭包的确没有转义(默认情况下),并显式添加了 @noescape
to someFunction
会产生一条警告,表明这是Swift 3.1中的默认设置。
Both closures are indeed non-escaping (by default), and explicitly adding @noescape
to someFunction
yields a warning indicating that this is the default in Swift 3.1.
我知道为什么
-更新-
屏幕截图:
-- UPDATE -- Screenshot attached:
推荐答案
如前所述,可选
闭包是转义
。不过,还有一个补充
As already said, Optional
closures are escaping
. An addition though:
Swift 3.1具有无需实际转义帮助程序功能,该功能在此处很有用。它仅将闭包标记为转义
以便在传递的闭包中使用,这样您就不必公开转义
Swift 3.1 has a withoutActuallyEscaping helper function that can be useful here. It marks a closure escaping
only for its use inside a passed closure, so that you don't have to expose the escaping
attribute to the function signature.
可以像这样使用:
extension Array {
private func someFunction(someClosure: (() -> Int)?) {
someClosure?()
}
func someOtherFunction(someOtherClosure: () -> Int) {
withoutActuallyEscaping(someOtherClosure) {
someFunction(someClosure: $0)
}
}
}
let x = [1, 2, 3]
x.someOtherFunction(someOtherClosure: { return 1 })
希望这很有帮助!
这篇关于Swift 3中的非转义闭包问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!