在雨燕1.2 @noescape属性 [英] @noescape attribute in Swift 1.2

查看:77
本文介绍了在雨燕1.2 @noescape属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有在斯威夫特1.2新特性与功能关闭参数,并作为文档说:

There is a new attribute in Swift 1.2 with closure parameters in functions, and as the documentation says:

这表明
  参数只会被调用(或者作为一个传递
  @
  noescape在一个呼叫参数),这意味着它不能
  活得比呼叫的寿命。

This indicates that the parameter is only ever called (or passed as an @ noescape parameter in a call), which means that it cannot outlive the lifetime of the call.

在我的理解,在此之前,我们可以使用 [弱个体经营] 不让封有很强的参考例如在执行时关闭它的阶级和自我可能是零或实例,但现在, @noescape 意味着,如果类deinitalized倒闭永远不会被执行。难道我理解正确吗?

In my understanding, before that, we could use [weak self] to not let the closure to have a strong reference to e.g. its class, and self could be nil or the instance when the closure is executed, but now, @noescape means that the closure will never be executed if the class is deinitalized. Am I understand it correctly?

如果我是正确的,为什么我会使用 @noescape 关闭insted的常规功能,当他们表现的非常相似?

And if I'm correct, why would I use a @noescape closure insted of a regular function, when they behaves very similar?

推荐答案

@noescape 可以用这样的:

func doIt(@noescape code: () -> ()) {
    /* what we CAN */

    // just call it
    code()
    // pass it to another function as another `@noescape` parameter
    doItMore(code)
    // capture it in another `@noescape` closure
    doItMore {
        code()
    }

    /* what we CANNOT do *****

    // pass it as a non-`@noescape` parameter
    dispatch_async(dispatch_get_main_queue(), code)
    // store it
    let _code:() -> () = code
    // capture it in another non-`@noescape` closure
    let __code = { code() }

    */
}

func doItMore(@noescape code: () -> ()) {}

添加 @noescape 保证封闭件将不会被存储在某个地方,在稍后的时间使用,或异步使用。

Adding @noescape guarantees that the closure will not be stored somewhere, used at a later time, or used asynchronously.

从图呼叫者的点,没有必要在意捕获变量的寿命,因为它们是被调用的函数内使用的或根本没有。作为奖励,我们可以用一个隐含的,打字自我拯救我们。

From the caller's point of view, there is no need to care about the lifetime of captured variables, as they are used within the called function or not at all. And as a bonus, we can use an implicit self, saving us from typing self..

func doIt(@noescape code: () -> ()) {
    code()
}

class Bar {
    var i = 0
    func some() {
        doIt {
            println(i)
            //      ^ we don't need `self.` anymore!
        }
    }
}

let bar = Bar()
bar.some() // -> outputs 0

另外,从编译器的点(如记录在<在

href=\"http://adcdownload.apple.com//Developer_Tools/X$c$c_6.3_beta/X$c$c_6.3_beta_Release_Notes.pdf\">release说明):

Also, from the compiler's point of view (as documented in release notes):

这使得一些小的性能优化。

This enables some minor performance optimizations.

这篇关于在雨燕1.2 @noescape属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆