How to prevent using weak self inside swift closure

If you had ever written a swift closure, you must have been met the situation about how to prevent self being strong reference inside closure. Usually we force ourselves to use [weak self], and then using “if let strongSelf = self” or “self?.” to let self can release while dealloc. But it’s really annoying, aren’t them?

old usage of closure

Swift 1.2 announced a syntax called “@noescape”, this attribute indicates that a closure will only live as long as the call so there is no possibility of retain cycles. That means you don’t have to worry about self being retained in closure and makes your code clean & easy-read.

closure use case with @noescape

Above screenshot presented the case how we use @noescape, this example will let swift developers can easily handle the multi-thread access code, and you don’t need to care about the reference problem inside closure because it s lifecycle depends on the call.

it will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the noescape declaration attribute do not require explicit use of self. for properties or methods.

References:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html#//apple_ref/doc/uid/TP40014097-CH35-ID348

http://www.russbishop.net/swift-1-2