Swift 5 结果类型 [英] Swift 5 Result type
问题描述
在 Swift 5 中,Apple 引入了 Result
类型.它是具有两种情况的通用枚举:
In Swift 5 Apple introduced Result
type. It's generic enum with two cases:
public enum Result<Success, Failure: Error> {
case success(Success), failure(Failure)
}
我个人习惯于在网络调用中使用两个单独的补全 success: Completion
和 failure: Completion
,但从我现在看到的情况来看,Apple 推动我们使用单个补全Result
输入然后在里面进行切换.那么这种带有 Result
的方法有什么优点呢?因为在很多情况下我可以省略错误处理并且不写这个switch
.谢谢.
Personally I used to two separate completions in network calls success: Completion
and failure: Completion
, but from what I see now, Apple pushing us to use single completion with Result
type and then inside perform switch. So what are advantages of this approach with Result
? Because in a lot of cases I can just omit error handling and don't write this switch
. Thanks.
推荐答案
当 Result
为 failure
时,您不应该省略情况.你不应该用 Result
来做,也不应该用失败的闭包来做.您应该处理错误.
You shouldn’t omit cases when Result
is failure
. You shouldn’t do it with Result
and you shouldn’t do it with your closure for failure. You should handle errors.
无论如何,引入 Result
类型是为了简化完成处理程序.您可以使用单个闭包来处理成功或失败(如果两个单独的闭包更好与否,则基于主要意见).Result
也是为错误处理而设计的.您可以简单地创建自己的符合 Error
的 enum
,然后您可以创建自己的错误案例.
Anyway, Result
type was introduced for simplifing completion handlers. You can have single closure for handling success or failure (primary-opinion based if two separate closures are better or not). Also Result
is designed for error handling. You can simply create your own enum
conforming to Error
and then you can create your own error cases.
这篇关于Swift 5 结果类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!