4

I have an extension Array in the form of:

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

    func someOtherFunction(someOtherClosure: () -> Int)
    {
        someFunction(someClosure: someOtherClosure)
    }
}

But I'm getting the error: Passing non-escaping parameter 'someOtherClosure' to function expecting an @escaping closure.

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.

Any idea why I'm getting this error?

-- UPDATE -- Screenshot attached: enter image description here

XmasRights
  • 1,427
  • 13
  • 21

3 Answers3

6

Optional closures are always escaping.

Why is that? That's because the optional (which is an enum) wraps the closure and internally saves it.

There is an excellent article about the quirks of @escaping here.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
5

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!

Sulthan
  • 128,090
  • 22
  • 218
  • 270
timaktimak
  • 1,380
  • 1
  • 12
  • 21
0

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)   
LimeRed
  • 1,278
  • 13
  • 18
  • 1
    `Optional` isn't opaque – it's an `enum` and is perfectly transparent. – Hamish Apr 04 '17 at 08:20
  • 1
    As @Hamish says, optional is `enum Optional { case some(T), case none }` Lots of the "quirks" of optionals become clear when you remember this. – JeremyP Apr 04 '17 at 08:35