Using @noescape to solve the "retention ring" problem with swift closures

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.