Swift Integer Overflow: Why Addition Can Crash
Understand why Swift arithmetic crashes on overflow and how to use overflow operators for wrapping behavior.
Adding two valid integers can crash your Swift app at runtime.
The Problem
1
2
3
let a: Int8 = 120
let b: Int8 = 10
let c = a + b // Crashes at runtime
Int8 holds values from -128 to 127. The result 130 exceeds this range, causing an overflow.
Why Swift Crashes
Swift’s arithmetic operators trap on overflow by default. Unlike C, which silently wraps to garbage values, Swift crashes immediately. This prevents subtle bugs where incorrect data propagates through your app.
Solution: Overflow Operators
Use &+, &-, and &* when you want wrapping behavior:
1
2
3
let a: Int8 = 120
let b: Int8 = 10
let c = a &+ b // c = -126 (wraps around)
The value wraps from 127 to -128 and continues counting, resulting in -126.
When to Use Overflow Operators
- Cryptographic algorithms requiring modular arithmetic
- Hash function implementations
- Low-level bit manipulation
- Performance-critical code where you’ve validated inputs
Quick Reference
| Operator | Behavior | Example (Int8: 127 + 1) |
|---|---|---|
+ | Traps on overflow | Crashes |
&+ | Wraps on overflow | -128 |
Standard operators are safer for typical app logic. Reserve overflow operators for intentional wrapping scenarios.
☕ Support My Work
If you found this post helpful and want to support more content like this, you can buy me a coffee!
Your support helps me continue creating useful articles and tips for fellow developers. Thank you! 🙏