[英]Return non-optional with .Success enum in Swift
Question: 题:
How do I define a function in a way that enforces a non-optional type to be passed when an enum that is also being passed in is of type .Success
? 当也要传入的枚举类型为.Success
如何以强制非可选类型的方式定义函数? If this can't be done, what's the best way to model this? 如果无法做到这一点,最好的建模方法是什么?
Context: 内容:
I'm making completion handler based wrapper around our API. 我正在围绕API进行基于完成处理程序的包装。 The parameters that are passed back to the handler include an enum
that gives a response status and a User
instance. 传递回处理程序的参数包括一个给出响应状态的enum
和一个User
实例。 The enum
is something like this: enum
是这样的:
enum ResponseStatus : Int {
case Success = 200
case InvalidParameters = 422
// and a few more
}
The method signature is like this: 方法签名是这样的:
static func createAccount(email: String, password: String, handler: (status: ResponseStatus, user: User?) -> ())
The problem with this is that .Success
could be returned along with nil
for the user, which shouldn't be able to happen. 问题在于, .Success
可能与nil
一起返回给用户,这不应该发生。
I want to be able to enforce that if .Success
is passed, user cannot be nil
. 我希望能够强制执行如果成功传递.Success
不能为nil
。 Can this be done? 能做到吗? If not, what's the best way to manage it? 如果没有,什么是最好的管理方式?
Thanks in advance for help. 在此先感谢您的帮助。
Great answers from both @AlexsanderAkers and @neilkimmett. @AlexsanderAkers和@neilkimmett都提供了不错的答案。 The only thing that separates them is Alex answered mere moments before Neil. 唯一使他们分开的是亚历克斯在尼尔面前的那一刻。 Thanks both! 谢谢你们!
What about something like this? 那这样的东西呢?
enum ResponseStatus<T> {
case Success(T)
case InvalidParameters
// other cases
}
Or you could have an Either
/ Result
type and only use the enum for the error scenarios? 或者,您可能具有Either
/ Result
类型,并且仅将枚举用于错误方案?
static func createAccount(email: String, password: String, handler: (Result<User, ResponseError>) -> Void) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.