Reputation: 16813
I am trying to inform user with a custom message as follows based on the HTTPURLResponse statusCode. However in the following implementation, I am having issue with StatusCode enum which is not properly implemented, I wonder how to fix that issue.
And also I wonder how to come up with a better approach to this type of generic issues?
enum StatusCode: Int, RawRepresentable {
case 400 = "It is a bad Request"
case 401 = "You are unauthorized"
case 403 = "You are forbidden"
case 404 = "Your request is not found, please try again"
}
func errorCheck(statusCode:Int){
if statusCode == StatusCode.400 {
print(StatusCode.400.rawValue)
}else if statusCode == StatusCode.404 {
print(StatusCode.404.rawValue)
}
}
Upvotes: 0
Views: 42
Reputation: 49610
What I think you're to do can be accomplished like so:
enum StatusCode: Int, RawRepresentable, CustomStringConvertible {
case e400 = 400
case e401 = 401
case e403 = 403
case e404 = 404
var description: String {
switch self {
case .e400: return "It is a bad Request"
case .e401: return "You are unauthorized"
case .e403: return "You are forbidden"
case .e404: return "Your request is not found, please try again"
}
}
}
Then you could use it like this:
func errorCheck(code: Int){
if let statusCode = StatusCode(rawValue: code) {
print(statusCode)
} else {
print("An unknown error ......")
}
}
Upvotes: 2