Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Error and NSError in Swift?

I am creating a library that should return errors so I'm wondering which one should use for my purposes.

UPDATE: I should clarify, the returned result will be from a asynchronous call so I need to inform to the user if there was an error and I would like to know which type I should use Error or NSError.

like image 831
Wilson Avatar asked Oct 21 '16 14:10

Wilson


People also ask

What is NSError in Swift?

Information about an error condition including a domain, a domain-specific error code, and application-specific information.

What is NSError domain?

The core attributes of an NSError object—or, simply, an error object—are an error domain, a domain-specific error code, and a “user info” dictionary containing objects related to the error, most significantly description and recovery strings.

What is NSError object made of?

The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.

What are exceptions in Swift?

In several ways errors in Swift are similar to exceptions in Objective-C and C++. Both errors and exceptions indicate that something didn't go as planned. The Swift error and exception breakpoints are useful to debug scenarios in which errors or exceptions are thrown.


1 Answers

NSError is a Cocoa class

An NSError object encapsulates information about an error condition in an extendable, object-oriented manner. It consists of a predefined error domain, a domain-specific error code, and a user info dictionary containing application-specific information.

Error is a Swift protocol which classes, structs and enums can and NSError does conform to.

A type representing an error value that can be thrown.

Any type that declares conformance to the Error protocol can be used to represent an error in Swift’s error handling system. Because the Error protocol has no requirements of its own, you can declare conformance on any custom type you create.

The quoted parts are the subtitle descriptions in the documentation.

The Swift’s error handling system is the pattern to catch errors using try - catch. It requires that the error to be caught is thrown by a method. This pattern is much more versatile than the traditional error handling using NSError instances. If you're planning not to implement try - catch you actually don't need the Error protocol.

like image 180
vadian Avatar answered Oct 06 '22 00:10

vadian