Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 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