微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 1.2中的@noescape属性

Swift 1.2中有一个新的属性,在函数中有闭包参数,并且文档说:

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.

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

如果我是正确的,为什么我会使用一个@noescape关闭一个普通的函数,当他们的行为非常相似?

@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保证闭包不会存储在某处,以后使用或异步使用。

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

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

另外,从编译器的角度来看(如release notes中所述):

This enables some minor performance optimizations.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐