加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 1.2中的@noescape属性

发布时间:2020-12-14 06:13:20 所属栏目:百科 来源:网络整理
导读: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. 在我的理解中,
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读