gpt4 book ai didi

swift - 为什么任何Error都可以无条件的转化为NSError?

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:27 24 4
gpt4 key购买 nike

很多时候,我会收到来自框架的 Swift Error 对象,这实际上是一个 NSError

为了访问它的信息(例如 code),我需要将它转换为 NSError:

(error as NSError).code == ....

为什么这只是一个无条件的 as?如果我设计自己的符合 Error 的错误类,它不一定是 NSError,那么这怎么可能是执行此转换的正确方法呢?

类型系统中是否存在某种特殊情况?这是一个表现得像向上转型的向下转型。

最佳答案

我相信将 Error 转换为 NSError 的能力已硬编码到编译器中,而实际的桥接是在 Swift 运行时中实现的。

runtime/ErrorObject.mm ,我发现了这条评论:

// This implements the object representation of the standard Error
// type, which represents recoverable errors in the language. This
// implementation is designed to interoperate efficiently with Cocoa libraries
// by:
// - ...
// - allowing a native Swift error to lazily "become" an NSError when
// passed into Cocoa, allowing for cheap Swift to Cocoa interop

this function :

/// Take an Error box and turn it into a valid NSError instance.
id
swift::_swift_stdlib_bridgeErrorToNSError(SwiftError *errorObject) {
...

// Otherwise, calculate the domain, code, and user info, and
// initialize the NSError.
auto value = SwiftError::getIndirectValue(&errorObject);
auto type = errorObject->getType();
auto witness = errorObject->getErrorConformance();

NSString *domain = getErrorDomainNSString(value, type, witness);
NSInteger code = getErrorCode(value, type, witness);
NSDictionary *userInfo = getErrorUserInfoNSDictionary(value, type, witness);

...
}

ErrorHandling.rst document说到理由:

It should be possible to turn an arbitrary Swift enum that conforms to Error into an NSError by using the qualified type name as the domain key, the enumerator as the error code, and turning the payload into user data.

(部分文档可能已过时。)

this is (我认为)类型检查器中至少有一个部分是对 Error 可转换为 NSError 的信息进行了编码(可能还有更多):

  // Check whether the type is an existential that contains
// Error. If so, it's bridged to NSError.
if (type->isExistentialWithError()) {
if (auto nsErrorDecl = getNSErrorDecl()) {
// The corresponding value type is Error.
if (bridgedValueType)
*bridgedValueType = getErrorDecl()->getDeclaredInterfaceType();

return nsErrorDecl->getDeclaredInterfaceType();
}
}

关于swift - 为什么任何Error都可以无条件的转化为NSError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51602907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com