Swift中的Error和NSError有什么区别? [英] What's the difference between Error and NSError in Swift?

查看:367
本文介绍了Swift中的Error和NSError有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应返回错误的库,所以我想知道应该使用哪个库.

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

更新: 我应该澄清一下,返回的结果将来自异步调用,因此我需要通知用户是否有错误,并且我想知道应该使用Error或NSError的类型.

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.

推荐答案

NSError是可可 class

NSError对象以可扩展的,面向对象的方式封装有关错误条件的信息.它由预定义的错误域,特定于域的错误代码和包含特定于应用程序的信息的用户信息字典组成.

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是Swift的协议,其中的类,结构和枚举可以并且NSError确实符合.

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.

任何声明符合Error协议的类型都可以用来表示Swift的错误处理系统中的错误.由于Error协议本身没有要求,因此您可以在创建的任何自定义类型上声明一致性.

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.

Swift的错误处理系统是使用try - catch捕获错误的模式.它要求通过某种方法捕获的错误为thrown.这种模式比使用NSError实例的传统错误处理功能更加通用.如果您计划实施try - catch,则实际上不需要Error协议.

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.

这篇关于Swift中的Error和NSError有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆