Trouble with non-escaping closures in Swift 3

后端 未结 3 2064
清酒与你
清酒与你 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:37

    As already said, Optional closures are escaping. An addition though:

    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.

    Can be used like this:

    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 })
    

    Hope this is helpful!

提交回复
热议问题