objective-c - 是否可以将 NULL NSError** 传递给抛出的 Swift 函数?

标签 objective-c swift error-handling

在 Objective-C 中,期望您可以将 NULL 传递给任何 NSError** 参数以忽略该错误。但是,当我尝试将 NULL 传递给抛出错误的 Swift 方法时,它会生成运行时错误。

// Thrower.swift
class Thrower: NSObject {
    static func throwError() throws {
        throw NSError(domain: "bla", code: 0, userInfo: nil)
    }
}

...

// AppDelegate.m
BOOL success = [Thrower throwErrorAndReturnError:NULL];

这会产生一个 EXC_BAD_INSTRUCTION 错误,这个堆栈:

enter image description here

我对这种行为感到有点惊讶。当您将 NULL 传递给这些方法之一时,我希望它可以工作,或者编译器会生成警告。

Swift 方法的生成 header 如下所示:

+ (BOOL)throwErrorAndReturnError:(NSError * __nullable * __null_unspecified)错误;

如果这不应该起作用,他们为什么不生成 NSError * __nullable * __nonnull,以便在您尝试传入可为 null 的 NSError* 时生成编译器警告?

我是否遗漏了什么,或者这只是预期的行为?

最佳答案

关于 WWDC'15 Session 401 (Swift 和 Objective-C 互操作性)Doug Gregor 说:

This means, 'I thought about it, I couldn't come to an answer.' The best thing to do is keep it implicitly unwrapped optional in Swift, keep it null-unspecified here.

所以,基本上,您的 null 被映射到 ImplicitlyUnwrappedOptional<ErrorType>.None ,这几乎可以解释崩溃的原因。

在上面的 session 中,他们提到了 NSError **假定为 nullable在两个指针上。显然他们改变了主意或者映射不对称,反正我觉得不对。

考虑到这种行为而不是 NSError * __nullable * __nonnull我会说这是一个错误,我会打开一个雷达。如果您这样做,请告诉我们,以便我们进行欺骗。

关于objective-c - 是否可以将 NULL NSError** 传递给抛出的 Swift 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35191651/

相关文章:

ios - 如何使用核心数据执行插入/更新

ios - 哪个线程调用 CFRunLoopStop(CFRunLoopGetCurrent())?

ios - y 轴的文本表示

ios - 无法在Swift 5的Mesibo聊天集成中从服务器接收消息

c++ - cin.fail()的错误处理问题

ios - 如何在UICollectionView中获取选定的CollectionViewCell?

iphone - 调用方法[self somemethod]时如何解决错误

ios - Bundle.main.url(forResource : "hello", withExtension: "html") 返回 nil

c# - Log4Net错误: “Failed to find configuration section log4net” AdoNetAppender

asp.net-mvc - ASP MVC-获取 Controller 级别的错误处理