2

In Objective-C, it's expected that you can pass in NULL to any NSError** parameter to ignore the error. However, when I try to pass NULL to a Swift method that throws an error, it generates a runtime error.

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

...

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

This generates an EXC_BAD_INSTRUCTION error, with this stack:

enter image description here

I'm a little surprised at this behavior. I would expect this to either work, or the compiler to generate a warning when you pass NULL to one of these methods.

Here's what the generated header of the Swift method looks like:

+ (BOOL)throwErrorAndReturnError:(NSError * __nullable * __null_unspecified)error;

If this was not supposed to work, why wouldn't they generate NSError * __nullable * __nonnull, so that a compiler warning is generated when you try to pass in a nullable NSError*?

Is there something I'm missing here, or is this just expected behavior?

1
  • The error throw is there for a reason:to help you with bugs, don't you think that is a good idea? Handling all potential errors is the job of a real developer, right?
    – zaph
    Feb 4, 2016 at 3:12

1 Answer 1

1

On WWDC'15 Session 401 (Swift and Objective-C Interoperability) Doug Gregor said:

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.

So, basically, your null is mapped to ImplicitlyUnwrappedOptional<ErrorType>.None, that pretty much explains the crash.

On the session above they mention NSError ** is assumed to be nullable on both pointers. Apparently they've changed their mind or the mapping is not symmetrical, anyway it looks wrong to me.

Considering that behavior and not being NSError * __nullable * __nonnull I'd say it's a bug, I'd open a radar. If you do please let us know so we can dupe it.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.