Trouble with non-escaping closures in Swift 3

后端 未结 3 2089
清酒与你
清酒与你 2021-01-19 03:48

I have an extension Array in the form of:

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


        
3条回答
  •  忘掉有多难
    2021-01-19 04:34

    The problem is that optionals (in this case (()-> Int)?) are an Enum which capture their value. If that value is a function, it must be used with @escaping because it is indeed captured by the optional. In your case it gets tricky because the closure captured by the optional automatically captures another closure. So someOtherClosure has to be marked @escaping as well.

    You can test the following code in a playground to confirm this:

    extension Array
    {
        private func someFunction(someClosure: () -> Int)
        {
            // Do Something
        }
    
        func someOtherFunction(someOtherClosure: () -> Int)
        {
            someFunction(someClosure: someOtherClosure)
        }
    }
    
    let f: ()->Int = { return 42 }
    
    [].someOtherFunction(someOtherClosure: f)   
    

提交回复
热议问题