When programming with Swift we often use closures, although closures are good, but inevitably bring "retention ring" issues, consider the following:
There is a loop function in an animation frame:
loop(duration:NSTimeInterval,reverse:Bool,animations:()->Bool )
Define an animation method in our own class, using this function:
class MyView:UIView{ func animations(){ loop(duration:0.5,reverse:true){ self.scale(1.25) } } func scale(scale:Double){...}}
You'll notice that the Self,loop function loop captured in the closure calls the closure every time, so that it retains self. The operations in the closures are in fact static, and there is no need to access them every time. If we only call a animations closure, take a snapshot of it to solve this problem, it will use the @noescape:
loop(duration:NSTimeInterval,reverse:Bool,@ noescape animations:()->Bool )
There is no retention ring problem, because the closure is only executed once, and the closure is bypassed even if a loop occurs. @noescape is a new role, but there are some places in the system library that are already in use, such as the reduce method we are familiar with:
func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using @noescape to solve the "retention ring" problem with swift closures