[ad_1]
I’ve an enum describing numerous error codes that may be returned from a server:
public enum LoginError: Int, Error {
case missingUsername = 30001
case missingPassword = 30002
case incorrectPassword = 30003
case unknownUser = 30005
case couldNotBeLoaded = 31002
case sessionExpired = 31001
case unknownError = 30000
}
The server returns the error within the response physique. I am decoding the end result and getting the error code, after which matching the error code with the enum:
let decoder = JSONDecoder()
let loginResult = strive decoder.decode(LoginResult.self, from: information)
if loginResult.success {
return .success(loginResult)
} else {
swap loginResult.errorCode as! Error {
case LoginError.incorrectPassword:
return .failure(.incorrectPassword)
case LoginError.missingUsername:
return .failure(.missingUsername)
case LoginError.missingPassword:
return .failure(.missingPassword)
case LoginError.unknownUser:
return .failure(.unknownUser)
case LoginError.couldNotBeLoaded:
return .failure(.couldNotBeLoaded)
case LoginError.sessionExpired:
return .failure(.sessionExpired)
default:
return .failure(.unknownError)
}
}
For one, this crashes as a result of I am unable to solid the LoginError Int sort to Error, but in addition, there should be a extra elegant means than this lengthy swap assertion. I really feel like there’s some primary little bit of Swift syntax I’ve missed right here. Is there a one-liner that would substitute this?
[ad_2]
