Swift 3 :Closure use of non-escaping parameter may allow it to escape

后端 未结 3 718
梦如初夏
梦如初夏 2020-12-15 22:05

I have the following function where I have completion handler but I\'m getting this error:

Closure use of non-escaping parameter may allow it to escape
         


        
3条回答
  •  太阳男子
    2020-12-15 22:27

    An "escaping" closure is a closure that can outlive the scope that it was created in. Escaping closures require special care around reference counting and memory management and can be harder to optimize.

    Prior to Swift 3, the default for closures was to assume that they were escaping. This meant that developers had to specifically identify closures that are known not to escape to allow the compiler to make optimizations. The community found that in fact, the compiler could easily find out by itself if a closure is escaping or not, and decided that an aggressive approach to escaping could result in faster code. The result is that closures are now assumed to be non-escaping, and you need to flag closures that are escaping with the @escaping attribute.

    In your case, the closure that URLSession.shared.dataTask accepts is itself an escaping closure, so if you use a closure inside of it, it also needs to be marked @escaping.

提交回复
热议问题