My question is derived from the following Japanese question. It's not my question, but I'm trying to answer the following problem but I cannot find the suitable answer.
https://teratail.com/questions/298998
The question above will be simpled like below.
func executetwice(operation:() -> Void) {
print(operation)
operation()
}
This compiler required to add @escaping
keyword after operation:
label, such as
func executetwice(operation: @escaping () -> Void) {
print(operation)
operation()
}
But in fact, it seems that operation
block does not escape from this block.
Another way,
func executetwice(operation:() -> Void) {
let f = operation as Any
operation()
}
also compiler requires to add @escaping
keyword. It is just upcasting to Any
.
In other case, just casting to same type, it seems to be error.
func executetwice(operation:() -> Void) {
let f = operation as () -> Void //Converting non-escaping value to '() -> Void' may allow it to escape
operation()
}
I'm not sure why I need to add @escaping
keyword with no escaping condition.
Just adding @escaping
keyword will be Ok, but I would like to know why the compiler required the keyword in this case.