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

18,068

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.

Share:
18,068
Wilson
Author by

Wilson

You can contact me at: [email protected]

Updated on June 08, 2022

Comments

  • Wilson
    Wilson almost 2 years

    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.

  • Wilson
    Wilson over 7 years
    Interesting so then I should use Error protocol as the type for returning errors from my library.
  • vadian
    vadian over 7 years
    If you are planning methods which throws errors, then yes.
  • Wilson
    Wilson over 7 years
    well in my case, it will be closures that will have an argument as an error.
  • Wilson
    Wilson over 7 years
    I understand but as far as I know try - catch doesn't work for asynchronous calls so that's why I intend to use an error as an argument.
  • vadian
    vadian over 7 years
    I wrote you don't need it but of course you can use it.
  • Wilson
    Wilson over 7 years
    mr. vadian thank you for taking the time to answer my question.
  • mfaani
    mfaani over 7 years
    wasn't errorType the protocol? What's the diff between errorType & error?
  • vadian
    vadian over 7 years
    ErrorType -> Swift 2, Error -> Swift 3 @Honey
  • Ricardo
    Ricardo about 3 years
    Or if you want to use Result