如何使用结果库处理无效成功案例(成功/失败) [英] How to handle Void success case with Result lib (success/failure)

查看:86
本文介绍了如何使用结果库处理无效成功案例(成功/失败)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:

我在我的应用程序的某些地方引入了结果框架(antitypical).例如,给定此功能:

I'm introducing a Result framework (antitypical) in some points of my app. In example, given this function:

func findItem(byId: Int, completion: (Item?,Error?) -> ());

foo.findItem(byId: 1) { item, error in
   guard let item = item else {
       // Error case
       handleError(error!)
       return;
   }
   // Success case
   handleSuccess(item)
}

我用Result这样实现它:

I implement it this way with Result:

func findItem(byId: Int, completion: Result<Item,Error>) -> ());

foo.findItem(byId: 1) { result in
   swith result {
      case let success(item):
         // Success case
         handleSuccess(item)
      case let failure(error):
         // Error case
         handleError(error!)
   }
}

问题 成功案例不返回任何结果时实现结果的正确方法是什么?像这样:

Question What is the correct way of implementing a result where the success case returns nothing?. Something like:

func deleteItem(byId: Int, completion: (Error?) -> ());

foo.deleteItem(byId: 1) { error in
   if let error = error {
       // Error case
       handleError(error)
       return;
   }
   // Success case
   handleSuccess()
}

在Java中,我将实现Result,这是在Swift中执行此操作的正确方法

In java I would implement a Result whats the correct way to do this in Swift

推荐答案

最好的方法就是您所做的事情:Error?其中nil表示成功.十分简单明了.

The best way is exactly what you've done: Error? where nil indicates success. It's quite clear and simple.

也就是说,另一个答案(也是我使用的答案)正好在您的问题中:如何使用Result处理Void成功案例."成功案例通过Void,因此通过Void:

That said, another answer (and one that I've used) is exactly in your question: "How to handle Void success case with Result." The success case passes Void, so pass Void:

Result<Void, Error>

无效"并不表示什么也不返回".这是Swift中的一种类型,它只有一个值:空元组().碰巧也是这种类型:

"Void" doesn't mean "returns nothing." It's a type in Swift, a type that has exactly one value: the empty tuple (). That also happens to be the type:

public typealias Void = ()

根据惯例,我们使用Void表示类型,使用()表示值.在Result中以这种方式使用Void有点奇怪的是语法.您结束时会出现类似这样的内容:

As a matter of convention, we use Void to mean the type, and () to mean the value. The one thing that's a bit strange about using Void this way in a Result is the syntax. You wind up with something like:

return .success(())

双括号有点丑陋并且有点混乱.因此,即使这与使用其他Result的代码很好地并行,在这种情况下,我通常也只使用Error?.不过,如果有很多,我会考虑为其创建一个新类型:

The double-parentheses are a little ugly and slightly confusing. So even though this is nicely parallel to other Result-using code, I typically just use Error? in this case. If I had a lot of it, though, I'd consider creating a new type for it:

enum VoidResult {
    case .success
    case .failure(Error)
}

这篇关于如何使用结果库处理无效成功案例(成功/失败)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆