ios - Trying to print a description of an Error (AKA ErrorType) enum -


i using enum inherits error (or errortype in swift 2) , trying use in such way can catch error , use print(error.description) print description of error.

this error enum looks like:

enum updateerror: error {     case noresults     case updateinprogress     case nosubredditsenabled     case setwallpapererror      var description: string {         switch self {         case .noresults:             return "no results found current size & aspect ratio constraints."         case .updateinprogress:             return "a wallpaper update in progress."         case .nosubredditsenabled:             return "no subreddits enabled."         case .setwallpapererror:             return "there error setting wallpaper."         }     }      // 1 of many nested enums     enum jsondownloaderror: error {         case timedout         case offline         case unknown          var description: string {             switch self {             case .timedout:                 return "the request reddit json data timed out."             case .offline:                 return "the request reddit json data failed because network offline."             case .unknown:                 return "the request reddit json data failed unknown reason."             }         }     }      // ... } 

an important thing note there few nested enums within updateerror won't work because nested enums aren't of updateerror type themselves:

do {     try functionthatthrowsupdateerror() } catch {     nslog((error as! updateerror).description) } 

is there better way of printing description of error without having check every type of updateerror occurred in catch statement?

you define (possibly empty) protocol, , conform errors it.

protocol descriptiveerror {    var description : string { } }  // specify descriptiveerror protocol in each enum 

you pattern match against protocol type.

do {   try functionthatthrowsupdateerror() } catch let error descriptiveerror {   print(error.description) } 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -