ios - 我们是否总是需要在闭包中调用完成处理程序?
问题描述
我有一个在我的闭包中被调用的完成处理程序。但是,只有在一切顺利时才会调用完成处理程序。在发生错误的情况下,完成处理程序永远不会被调用。
func product(with id: String, _ completion: @escaping (Product) -> ()) {
// Make a network request for the product
...
if (product) {
completion(product)
}
}
这是一个糟糕的设计吗?我最近收到评论,即使出现错误也需要调用完成处理程序,否则调用者将无限期等待。我以前从未听说过,现在我想知道这是否适用于 Swift。
解决方案
严格来说,来电者根本不等待。闭包中的代码将或不会被执行。
然而,返回错误也是一个好习惯。
一个聪明的方法是Result
类型
func product(with id: String, completion: @escaping (Result<Product,Error>) -> Void) {
// Make a network request for the product
...
if error = error { completion(.failure(error)); return }
if product {
completion(.success(product))
} else {
let error = // create some other error
completion(.failure(error))
}
}
并称它为
product(with: "Foo") { result in
switch result {
case .success(let product): // do something with the product
case .failure(let error): // do something with the error
}
}
注意:completion
函数声明中前面的下划线是没有意义的。
推荐阅读
- python - 没有提供静态文件夹的烧瓶轮文件
- javascript - 手机上无限连续循环滚动
- spring-boot - 如何调试永远不会完成的 Mono
- firebase - Firebase/Firestore 静态加密级别
- postgresql - SQL 中的 MIN 函数未按预期工作
- sql-server - 无法将 Polybase 连接到 PostgreSQL
- c# - 更改表达式的返回类型
> 具有值类型 - javascript - 如何在打字稿中使用角度十进制管道
- reactjs - 如何从上下文中使用 ref.current?
- firebase - Flutter 无法识别 FirebaseFirestore(Android Studio)