Random EXC_BAD_ACCESS crash in Swift

  • 1 Min. Read.

When porting a Spritekit game (written in Swift) to tvOS I stumbled on some random EXC_BAD_ACCESS crashes, which had me baffled.

exc_bad_access on super.init()
exc_bad_access on super.init()

Looking for the issue

After some intense debugging I couldn’t pinpoint any issues that lead to the crash and the stack trace wasn’t exactly helpful either. When switching to the release Build Configuration the problem was gone, which lead me to believe this has got to be settings related.

The Solution

After checking out the Build Settings – The Swift Compiler settings to be specific – I found a solution. Setting the Optimization Level to Fast, Whole Module Optimization [-O -whole-module-optimization] fixed this issue for me, but another issue appeared.

Optimization level settings
Optimization level settings

The solution – Part 2

Because the project was compiled with optimization enabled, I got the following message when I set a breakpoint:

Switching the Optimization Level to Fast [-O], provides the best of both worlds. The crash hasn’t occurred since, and I’m still able to use the stepping commands in the debugger.

An overview of the optimization level values
An overview of the optimization level values

TLDR

EXC_BAD_ACCESS crash caused by Swift Compiler can be fixed by setting the Optimization Level to Fast [-O].