LocalizedError, RecoverableError, CustomNSError
Swift 2 introduced error handling by way of the throws, do, try and catch keywords. It was designed to work hand-in-hand with Cocoa error handling conventions, such that any type conforming to the ErrorProtocol protocol (since renamed to Error) was implicitly bridged to NSError and Objective-C methods with an NSError** parameter, were imported by Swift as throwing methods.
→ nshipster.com/swift-foundation-error-protocols/
Swift’s error handling works well with Cocoa’s NSError system. Swift 3 added three little-known protocols to make this link even better:
LocalizedError
Gives user-friendly messages: title, reason, recovery suggestion, and help text. Adopt it on your error types so any view controller can build an alert without knowing the error details.RecoverableError
Lets the system show a list of recovery choices (mainly useful on macOS). The user picks an option and the app tries to fix the problem.CustomNSError
Turns a Swift error into a real NSError with a domain, code, and userInfo dictionary. This is required for macOS recovery alerts to work properly.
In practice, make your errors conform to LocalizedError for clean user messages and, if needed, to CustomNSError for full Cocoa compatibility. RecoverableError is handy when you want to offer “Try again / Cancel” style options.
Using these protocols keeps error handling tidy, reusable, and fully compatible with Apple’s platforms.
Category:
Tag:
Year: