Last active
March 20, 2023 02:21
-
-
Save hboon/5c8e258aaedfc896688d473a4cabee79 to your computer and use it in GitHub Desktop.
Implementing types that conform to LocalizedError in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
do this in the module (i.e do not make it conform to
LocalizedError
in the module) :and this in the main app (conform to
LocalizedError
in the app: