I have encountered a situation when a closure may be called inside the function f1
(in which the closure is passed to) or it may be passed to some other function f2
.
So now I wonder how should I define escaping behaviour of this closure. I mean should I put @escaping
or not?
Sample function:
func f1(_ completionHandler: ()->()){
if someFlag == true{
completionHandler()
return
}
f2(completionHandler)
}
func f2(_ completionHandler: ()->()){
// some other magic
}
Sorry if there are some syntactical errors, (typed the methods here), my question is, what should be type attribute of completionHandler for function f1
?
The rule for when you need @escaping
is simple – if a closure function argument can escape the lifetime of the function call, it needs to be marked as @escaping
(the compiler simply won't let you compile it otherwise).
In your example code, completionHandler
is not marked as @escaping
in f2
– therefore it cannot escape the lifetime of f2
. Therefore it cannot possibly escape the lifetime of f1
either, thus you don't need to mark f1
's completionHandler
as @escaping
.
If however, f2
's completionHandler
could escape the lifetime of f2
, then you would have to mark both f2
and f1
's parameters as @escaping
as it could escape the lifetime of both calls.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.