解决Swift 3中的非转义闭包问题

Xma*_*hts 4 closures swift

extension Array的形式是:

extension Array
{
    private func someFunction(someClosure: (() -> Int)?)
    {
        // Do Something
    }

    func someOtherFunction(someOtherClosure: () -> Int)
    {
        someFunction(someClosure: someOtherClosure)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:Passing non-escaping parameter 'someOtherClosure' to function expecting an @escaping closure.

这两个闭包确实是非转义的(默认情况下),并且显式地添加@noescapesomeFunction产生警告,指示这是Swift 3.1中的默认值.

知道我为什么会收到这个错误吗?

- 更新 - 附带截图: 在此输入图像描述

Sul*_*han 6

可选的闭包总是逃脱.

这是为什么?那是因为可选(它是一个枚举)包装闭包并在内部保存它.

关于@escaping 这里的怪癖有一篇很好的文章.


tim*_*mak 5

如前所述,Optional关闭是escaping.另外一个补充:

Swift 3.1有一个withoutActuallyEscaping辅助函数,在这里很有用.它escaping仅为在通过的闭包内使用它标记了一个闭包,因此您不必将该escaping属性公开给函数签名.

可以像这样使用:

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 })
Run Code Online (Sandbox Code Playgroud)

希望这有用!