Swift 1.2中的@noescape属性 [英] @noescape attribute in Swift 1.2

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

问题描述

Swift 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.

根据我的理解,在此之前,我们可以使用 [weak self] 有强烈的参考它的类和self可以是nil或者执行闭包时的实例,但是现在, @noescape 意味着如果类被去离子化,闭包将永远不会被执行。我是否理解正确?

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

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(code: @noescape () -> ()) {
    /* 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(code: @noescape () -> ()) {}

添加 @noescape 可确保闭包不会存储在某处,以后使用或异步使用。

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

从调用者的角度来看,没有必要关心捕获的变量的生命周期,因为它们在被调用函数中使用或根本不使用。作为一个奖励,我们可以使用隐式 self ,从而节省我们输入 self。

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(code: @noescape () -> ()) {
    code()
}

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

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

此外,从编译器的角度来看(如发行说明):

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


这可以进行一些次要的性能优化。

This enables some minor performance optimizations.

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

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