莫名其妙的标记之@noescape

Swift 中经常遇到一些不熟悉的关键字, 例如@autoclosure@noescape...等等, 为什么要加这样的关键字, 我自己写方法的时候什么时候要加, 什么时候不加, 都是应该考虑的问题, 所以打算写一系列文章来介绍一下这些关键字.

@noescape

@noescape 用来标记一个闭包, 用法如下

func hostFunc(@noescape closure: () -> ()) -> Void

@noescape字面意思是无法逃脱. 在上例中, closure 被@noescape修饰, 则声明 closure的生命周期不能超过 hostFunc, 并且, closure不能被hostFunc中的其他闭包捕获(也就是强持有).

用例
func hostFunc(@noescape closure: () -> ()) -> Void {
    //以下编译出错, closure 被修饰后, 不能被其他异步线程捕获
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        closure()
    }
}

 

原文地址:https://www.cnblogs.com/qing123/p/6344834.html