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

雨燕双飞 提交于 2019-12-09 04:19:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40179441/whats-the-difference-between-error-and-nserror-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!