爲什麼可選類型的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

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