Skip to content

Instantly share code, notes, and snippets.

@hboon
Last active March 20, 2023 02:21
Show Gist options
  • Save hboon/5c8e258aaedfc896688d473a4cabee79 to your computer and use it in GitHub Desktop.
Save hboon/5c8e258aaedfc896688d473a4cabee79 to your computer and use it in GitHub Desktop.
Implementing types that conform to LocalizedError in Swift
//Proper way to implement error types. Implement `errorDescription`, not `localizedDescription` and the global handler `getErrorMessage(error: Error)` is easy to implement, not need a stupid switch case
//Key is implement `errorDescription` instead of `localizedDescription` and must not implement `localizedDescription` at all
import Foundation
struct E1: LocalizedError {
var errorDescription: String? {
return "E1's errorDescription"
}
}
struct E2: LocalizedError {
var errorDescription: String? {
return "E2's errorDescription"
}
}
let e = E1()
let f: LocalizedError = e
let g: Error = e
print("errorDescription:")
print(e.errorDescription)
print(f.errorDescription)
//print(g.errorDescription)
print("\nlocalizedDescription:")
print(e.localizedDescription)
print(f.localizedDescription)
print(g.localizedDescription)
func getErrorMessage(error: Error) -> String {
return error.localizedDescription //making `getErrorMessage(error:)` unnecessary
}
print("\ngetErrorMessage:")
print(getErrorMessage(error: E1()))
print(getErrorMessage(error: E2()))
@hboon
Copy link
Author

hboon commented Mar 20, 2023

And if the error type is defined in a module (eg. Cocoapods) and only the main app provide the localized strings, then:

instead of this in the module:

struct E1: LocalizedError {
    var errorDescription: String? {
      return "E1's errorDescription"
    }
}

do this in the module (i.e do not make it conform to LocalizedError in the module) :

struct E1: Error {
}

and this in the main app (conform to LocalizedError in the app:

extension E1: LocalizedError {
    var errorDescription: String? {
      return "E1's localized errorDescription" //using R.string.localizable.xxx()
    }
}

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