Skip to content

Instantly share code, notes, and snippets.

@bleft
Last active April 29, 2020 12:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bleft/d733562a649e03d073cd707a64df4b43 to your computer and use it in GitHub Desktop.
Save bleft/d733562a649e03d073cd707a64df4b43 to your computer and use it in GitHub Desktop.
custom enum errors with localizedDescription
// sepcifiy your errors
enum MyCustomError : Error {
case customError
case missingProperty
var localizedDescription: String {
switch self {
case .urlCouldNotBeCreated:
return NSLocalizedString("MyCustomErrorCcustomError", value: "a localized error message", comment: "")
case .missingProperty:
return NSLocalizedString("MyCustomErrorMissingProperty", value: "Missing coordinates", comment: "")
}
}
}
// use your error
func demo() throws {
throw MyCustomError.customError
}
// catch your error
do {
try demo()
} catch let error as MyCustomError {
print(error.localizedDescription)
}
@ftiff
Copy link

ftiff commented Jul 19, 2017

Hi,
According to https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md
You need something like:

enum MyCustomError : LocalizedError {
    case customError
    case missingProperty
    
    var errorDescription: String? {
        switch self {
        case .urlCouldNotBeCreated:
            return NSLocalizedString("MyCustomErrorCcustomError", value: "a localized error message", comment: "")
        case .missingProperty:
            return NSLocalizedString("MyCustomErrorMissingProperty", value: "Missing coordinates", comment: "")
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment