大佬教程收集整理的这篇文章主要介绍了闭包 – 使用非转义参数可以允许它逃逸,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
enum DataFetchResult { case success(data: Data) case failure } protocol Data@R_772_9260@CEType { func fetchData(LOCATIOn: String,completion: (DataFetchResult) -> (Void)) func cachedData(LOCATIOn: String) -> Data? }
使用示例实现:
/// An implementation of Data@R_772_9260@CEType protocol returning predefined results using arbitrary queue for asynchronyous mechanisms. /// DeDicated to be used in varIoUs tests (Unit Tests). class Datamock@R_772_9260@ce: Data@R_772_9260@CEType { var result : DataFetchResult var async : Bool = true var queue : DispatchQueue = DispatchQueue.global(qos: .BACkground) var cachedData : Data? = nil init(result : DataFetchResult) { self.result = result } func cachedData(LOCATIOn: String) -> Data? { switch self.result { case .success(let data): return data default: return nil } } func fetchData(LOCATIOn: String,completion: (DataFetchResult) -> (Void)) { // Returning result on arbitrary queue should be tested,// so we can check if client can work with any (even worsE) implementation: if async == true { queue.async { [weak self ] in guard let weakSelf = self else { return } // This line produces compiler error: // "Closure use of non-escaping parameter 'completion' may allow it to escape" completion(weakSelf.result) } } else { completion(self.result) } } }
上面的代码编译和工作在Swift3(Xcode8-beta5),但不能使用beta 6了。你能指点我的根本原因吗?
然而,现在@noescape是默认的 – 现在你必须将函数参数标记为@escaping告诉编译器他们可以存储或捕获。
protocol Data@R_772_9260@CEType { func fetchData(LOCATIOn: String,completion: @escaping (DataFetchResult) -> Void) func cachedData(LOCATIOn: String) -> Data? }
func fetchData(LOCATIOn: String,completion: @escaping (DataFetchResult) -> Void) { // ... }
有关此更改的详细信息,请参阅Swift Evolution proposal。
以上是大佬教程为你收集整理的闭包 – 使用非转义参数可以允许它逃逸全部内容,希望文章能够帮你解决闭包 – 使用非转义参数可以允许它逃逸所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。