An odd error: "Escaping closure captures mutating 'self'"

@tem I thought a bit more about the above statement after I replied to you. I think it's both correct and incorrect.

It's incorrect in theory. According to the Swift language book, a closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. So just saving a closure in some variable doesn't necessarily mean it's leaked outside the function. For example, that variable may be a local variable. For the same reason, an optional closure doesn't have to be escaping. I guess this was probably what you meant above? There was discussion and a proposal to change this behavior.

It's correct because that's the behavior in current implementation. It seems that, to save a closure in any variable, the closure must be escaping. See this example:

struct Struct {
    var callback: () -> Void
}

func test(_ callback:() -> Void) { //  Not working. Must be @escaping
    let x = Struct(callback: callback)
}

It is true for non-struct variable also:

func test(_ callback: () -> Void) {  //  Not working. Must be @escaping
    let x: () -> Void = callback 
    x()
}
1 Like