Swift Errors and the NSError Bridge
Swift's modern `Error` protocol and Objective-C's `NSError` are different, but Swift automatically "bridges" them. This is key when calling older Apple APIs, which throw `NSError`s.
WHY IT EXISTS Swift was designed for seamless interoperability with existing Objective-C codebases. Objective-C uses a class, NSError, for error handling, typically passed as an out-parameter (NSError **). Swift introduced the more modern Error protocol and do-try-catch syntax, requiring a robust "bridge" to make the two systems communicate effectively.
THE MENTAL MODEL Think of the NSError bridge as a translator at the border between Swift and Objective-C. When a Swift function calls an old Objective-C method that can fail, the translator converts the potential NSError object into a thrown Swift Error. When you catch it, you're handling what looks like a native Swift error, but it's often an NSError wearing a Swift Error costume.
HOW IT WORKS Swift automatically imports Objective-C methods with an NSError** parameter as functions that throw. When you call one and an error occurs, your catch block receives a generic Error object. To get meaningful details, you must cast this object to NSError. Once cast, you can inspect its three key properties: domain (a string identifying the error's source, like NSURLErrorDomain), code (an integer for the specific error), and userInfo (a dictionary for extra context).
WHEN TO USE IT You'll interact with this bridge constantly when using Apple's platform frameworks like Foundation, UIKit, or AppKit. Core operations like file I/O with FileManager or network requests with URLSession all use NSError under the hood. Any time you catch an error from a system API, you should attempt to cast it to NSError to properly diagnose and handle the failure.
WHEN NOT TO USE IT For pure Swift code—your own application logic or libraries without Objective-C dependencies—you should define custom error types, typically enums conforming to the Error protocol. This approach is more type-safe and expressive. The NSError bridge is a tool for interoperability, not the preferred model for designing new error-handling logic in Swift.
ONE CANONICAL EXAMPLE A URLSession data task is a classic case. The completion handler provides an optional Error. If an error exists, it's an NSError. You would cast it to inspect its code property and compare it against predefined constants like NSURLErrorNotConnectedToInternet or NSURLErrorTimedOut to determine the specific cause of the network failure and update the UI accordingly.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.