Is a closure enum associated value escaping?

Hi, community:

Today a Swift question came up to me. Is a closure enum associated value considered to be an escaping closure?

an example:

enum Operation {
    case opA(()-> Void)
    case opB(()-> Void)
}

Thanks in advance

Answered by Scott in 747319022

You should consider the closure to be escaping. The syntax for declaring an enum associated value isn’t quite the same as an initializer so there’s nowhere to put the @escaping keyword, but the effect is the same: the closure is retained by the enum value and may be called later. If you do this in a class context and implicitly reference self then you’ll get the familiar warning about that:

class Foo: NSObject {
    func foo() {
        _ = Operation.opA {
            print(description) // ERROR: Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit
        }
    }
}  

escaping closure is relative to a function closure parameter.

What would it mean here ?

I've written this snippet to analyse, but I don't think it really relate to escaping:

var x = 0

enum Operation2 {
    case opA((Int)-> Int)
    case opB((Int)-> Int)
}

var handlerA2 : (Int)-> Int = { x in
    print("handlerA2", x)
    return x * 1000
}
let op2 = Operation2.opA(handlerA2)

var calledClosure : ((Int)-> Int)?
switch op2 {
    case let .opA(closureA) :
        print("Call opA")
        x = closureA(10)
        calledClosure = closureA
    case let .opB(closureB) :
        print("Call opB")
        closureB(40)
}
print("op2", x)
print("called:", calledClosure!(50))
Accepted Answer

You should consider the closure to be escaping. The syntax for declaring an enum associated value isn’t quite the same as an initializer so there’s nowhere to put the @escaping keyword, but the effect is the same: the closure is retained by the enum value and may be called later. If you do this in a class context and implicitly reference self then you’ll get the familiar warning about that:

class Foo: NSObject {
    func foo() {
        _ = Operation.opA {
            print(description) // ERROR: Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit
        }
    }
}  
Is a closure enum associated value escaping?
 
 
Q