Playground出现EXC_BAD_INSTRUCTION错误如何解决?
Hey there! That red stop sign and EXC_BAD_INSTRUCTION error can be super frustrating—especially when your values look like they’re working fine. Let’s walk through the most common fixes to get your Playground running smoothly again:
Common Causes & Solutions
1. Hunt Down Force Unwraps (!)
This is the #1 culprit for this error. If you’re force-unwrapping an optional that’s actually nil, Playground will throw this error even if the output seems okay. Instead of using !:
- Use optional binding to safely unwrap values:
if let safeValue = optionalValue { // Use safeValue here without risk } else { // Handle the nil case gracefully } - Or provide a default value with the nil-coalescing operator:
let safeValue = optionalValue ?? "Fallback Value"
2. Check for Array/Collection Index Out of Bounds
Accessing an index that doesn’t exist (like myArray[5] when the array only has 3 elements) will trigger this error. To fix:
- Avoid hardcoding indices—use
myArray.first,myArray.last, or iterate over elements instead. - Add a safety check before accessing an index:
if index >= 0 && index < myArray.count { let value = myArray[index] }
3. Fix Math Operation Exceptions
Dividing by zero, calculating NaN, or generating infinite values can also cause this error. Always validate your inputs first:
let denominator = 0 if denominator != 0 { let result = 10 / denominator } else { // Handle division by zero instead of letting it crash }
4. Reset Playground’s Glitchy State
Sometimes Playground gets stuck with cached state or random glitches. Try these quick resets:
- Close and reopen your Playground file.
- Clean the build folder: Go to
Product > Clean Build Folder(or pressCmd + Shift + K). - Restart Xcode entirely—occasionally the environment just needs a fresh start.
5. Debug Step-by-Step
Even if values look normal, hidden issues might be lurking. Add breakpoints to your code (click the gutter next to lines) and use the debug navigator to inspect variables as you run each line. This will help you spot when an optional becomes nil or an index goes out of bounds before the final line crashes.
Remember, the thread return -x command just resets you to the previous state—it doesn’t fix the underlying problem. Tracking down the root cause is key to making the error disappear for good.
内容的提问来源于stack exchange,提问作者Beth.larson1977

