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
? 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. The parameters that are passed back to the handler include an enum
that gives a response status and a User
instance. The enum
is something like this:
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.
I want to be able to enforce that if .Success
is passed, user cannot be 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. 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?
static func createAccount(email: String, password: String, handler: (Result<User, ResponseError>) -> Void) { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.