为什么可选类型的closure参数不需要加@escaping

在传参时,如果closure参数是在当前函数作用域执行完之前调用的,closure是非逃逸闭包;如果是在作用域以外的地方调用,则是逃逸闭包。
在我们使用时,发现如果传参数是可选的闭包时,加上@escaping会报错Closure is already escaping in optional type argument

static func dismiss(onCompletion: @escaping VoidFunction?) {
   // 报错Closure is already escaping in optional type argument
}

原因是:
Actually, since Swift 3 has been released, the closure will be "escaped" if it's declared in enum, struct or class by default.

Obviously, Optional is enum. 所以可选类型的闭包参数本身就是逃逸闭包,不需要再加@escaping

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章