My Swift application running in iOS simulator is being stopped in debugger with runtime error EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, sub code=0x0)
.
According to the WWDC 2014 Session 409 this is typically due to assertion failure.
In the current development Beta version of Xcode 6, the debugger’s stack trace and the above error does not provide enough information to see what the issue is. How do I find out where the problem is?
It appears that the most common source of this error (at the time of this writing: Xcode 6 Beta 1) is that some implicitly unwrapped optional property or variable is nil
.
For convenience, most Objective-C API are bridged to Swift with implicitly unwrapped optionals. They are denoted by exclamation mark behind the type declaration: AnyObject[]!
If the debugger stops in your code, double-check that line and look for implicitly unwrapped optionals that could be nil
there.
Sometimes the debugger stops with that runtime error deep in Swift system library. This happens for example when you pass a closure to collection methods like filter
, map
, reduce
et al. The runtime error then occurs at the call site of those library functions, but the definition might be in different parts of your code, where you defined the function/closure. Look there for implicitly unwrapped optionals that might be nil at runtime.
To guard agains these kinds of error be aware that even though Swift compiler will not force you to handle the potential nil
values returned from Cocoa, you should use optional binding, optional chaining
or optional downcasting wherever the return value from Objective-C land might be nil
.
Let’s hope that future versions of Swift compiler will start emitting more helpful diagnostic messages and errors for this common type of problem!
I have found (after many hours) that this error can appear on the wrong line.
For example
As you can see the app is crashing where I am checking for nil, but then 'continuing' through because it prints the statements. It then goes 'backwards' and crashes.
I've come to the conclusion that there is a source-mapping bug in XCode (7) where a nil variable is un-wrapped. In this case, I had a variable (much farther down in my code) that was nil and being unwrapped.
The problem of course is that the compiler didn't flag the actual variable that was nil, it flagged something else entirely.
So if you run into this nasty bug, go through all possible variables that can be nil and check them for unwrapping. You are likely unwrapping a nil, its just not the one the compiler says.
As mentioned in the comment there is compiler optimization. Here is a link to fix the issue (and find the route cause of the crash)
xcode 6.1 how to disable optimization (Swift)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With