Swift Integer Overflow in Coding Interviews: The Complete Guide

- Swift's
Intis always 64-bit on modern devices and LeetCode servers, giving a max of 9,223,372,036,854,775,807 — no need forInt64explicitly - Standard arithmetic traps on overflow in both Debug and Release builds; the crash is intentional, not a failure
- Binary search midpoint: always write
lo + (hi - lo) / 2instead of(lo + hi) / 2to eliminate addition overflow risk - Overflow operators (
&+,&-,&*) wrap without crashing for intentional modular arithmetic like hash functions addingReportingOverflowreturns a(partialValue, overflow: Bool)tuple so you can detect overflow programmatically without terminatingInt.min / -1traps because the mathematical result exceedsInt.max; guard explicitly when dividing by potentially negative values- Narrowing conversions (
Int32(x)) crash if the value doesn't fit; useInt32(exactly: x)for a safe optional instead
Your code passes the sample tests. The LeetCode judge runs the big ones. Fatal error: arithmetic operation overflowed. Your terminal is red. Your confidence is gone. And somewhere, a Go developer is laughing because their code silently returned the wrong answer and they'll never know why.
Swift doesn't quietly corrupt your result on overflow. It crashes. Loud, immediate, with a stack trace pointing at exactly the guilty line. That's not a bug in Swift. That's the design, and once you understand it, it's almost always working in your favor.
Meet Swift's Int
In Swift, Int is always pointer-sized: 64 bits on every modern device and on LeetCode's judging servers.
That means Int.max is 9,223,372,036,854,775,807 and Int.min is -9,223,372,036,854,775,808. For the vast majority of interview problems, that range is more than enough. You won't reach for Int64 because Int is already Int64 on every platform that matters.
Swift also ships fixed-width types when you need to care about bit counts:
| Type | Size | Min | Max |
|---|---|---|---|
Int8 | 8-bit | -128 | 127 |
Int16 | 16-bit | -32,768 | 32,767 |
Int32 | 32-bit | -2,147,483,648 | 2,147,483,647 |
Int64 / Int | 64-bit | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
Problems that specify Int32 constraints are still safe with Swift's Int. The fixed-width types come up for serialization, bit-packing, or when a problem explicitly caps you to a smaller range.
Swift Crashes on Overflow. That's the Design.
C++ treats signed integer overflow as undefined behavior. The compiler gets to assume it never happens, and when it does, you get instructions that make no sense and a bug that only manifests at 3 a.m. Go silently wraps. Swift made a different call.
Standard arithmetic operators in Swift trap on overflow in both Debug and Release builds.
var x: Int8 = 127 x += 1 // Fatal error: arithmetic operation overflowed
That's not a subtle wrong answer that slips through small test cases and baffles you when the judge disagrees. It's a crash, right now, on the exact line that caused the problem.
In a coding interview, this is genuinely useful. The alternative is a C++ or Go bug that produces a plausible-looking wrong number, your output looks almost right, and you spend 10 minutes convinced the algorithm is correct while the real issue is arithmetic.

Swift's fatal error is the most honest outcome. The other two will waste your debugging time.
The Binary Search Bug You Need to Fix by Default
The most common overflow spot in interview code is the midpoint calculation. Every binary search tutorial writes this first:
// Works fine for 64-bit indices, blows up when hi gets into the billions let mid = (lo + hi) / 2
With 64-bit Int, you'd need lo + hi to exceed 9.2 × 10¹⁸ before that addition overflows. For array indices, that's not happening. But problems that binary-search over a computed range (capacities, pile sizes, shipping weights) can push bounds into the billions, and then the sum can overflow before you divide.
Get into the habit of writing the safe version regardless:
let mid = lo + (hi - lo) / 2
Same result. Zero overflow risk. Three extra characters. Interviewers who know their binary search bugs will recognize this immediately as the kind of thing you learn by getting burned once and never forgetting.
The Wrapping Operators: Swift's "I Know What I'm Doing" Mode
Sometimes you genuinely need modular wraparound. Hash functions are the classic case. Swift ships overflow operators specifically for this:
let x: Int8 = 127 let wrapped = x &+ 1 // = -128, wraps cleanly, no crash // All three arithmetic ops have wrapping versions a &+ b // add with wrapping a &- b // subtract with wrapping a &* b // multiply with wrapping
The & prefix means "yes, I want this to wrap." Swift is not going to stop you.
You won't reach for these in most DSA problems. They exist for intentional bit manipulation and low-level arithmetic. If you're using &+ to silence a crash in normal arithmetic, the crash was trying to tell you something. Listen to it.
Overflow Without the Crime Scene
Swift also lets you do arithmetic and inspect whether overflow occurred, without crashing either way:
let (result, overflowed) = Int.max.addingReportingOverflow(1) // result = Int.min (the wrapped value), overflowed = true let a = 1_000_000_000 let (product, didOverflow) = a.multipliedReportingOverflow(by: a) // product = -5765169126539689984, didOverflow = true
The four methods:
.addingReportingOverflow(_:).subtractingReportingOverflow(_:).multipliedReportingOverflow(by:).dividedReportingOverflow(by:)
Each returns (partialValue: T, overflow: Bool). Use these when you need to signal overflow to a caller rather than terminating the program. In pure interview code you'll mostly use safe arithmetic patterns. But knowing these exist tells the interviewer you understand Swift's overflow model rather than just avoiding crashes by accident.
Int.max and Int.min: Useful Until You Do Math on Them
These two constants show up everywhere in interview code:
Int.max // 9,223,372,036,854,775,807 Int.min // -9,223,372,036,854,775,808
Write Int.max and Int.min, not magic numbers. They're readable, correct regardless of architecture, and you won't mistype a digit when you're nervous and the clock is running.
The standard pattern for tracking a running minimum or maximum:
var smallest = Int.max var largest = Int.min for num in nums { smallest = min(smallest, num) largest = max(largest, num) }
The trap: doing arithmetic with Int.max or Int.min directly. Int.max + 1 crashes. If you need a sentinel that still has arithmetic headroom, Int.max / 2 is the common workaround. You can add reasonable values to it without immediately triggering the trap.
Division: Two Ways to Ruin Your Day
Division by zero in Swift is always a runtime crash, regardless of build configuration:
let x = 10 / 0 // Fatal error: division by zero
Check your denominator before dividing, especially when it derives from array contents or the problem's input values. This is one of those bugs that never shows up on the happy path and always shows up in the judge's edge case set.
The less obvious trap is Int.min / -1. Mathematically, the result would be 9,223,372,036,854,775,808, one more than Int.max. Swift can't store it:
let x = Int.min / -1 // Fatal error: arithmetic overflow
If you're writing a general-purpose division function that handles arbitrary inputs, guard against both:
func safeDivide(_ a: Int, _ b: Int) -> Int? { guard b != 0 else { return nil } guard !(a == Int.min && b == -1) else { return nil } return a / b }
Integer division truncates toward zero. 7 / 2 is 3, -7 / 2 is -3. The remainder operator follows the sign of the dividend: -7 % 3 is -1.
Where Swift Integer Overflow Bites You on LeetCode
Large Multiplications in Counting Problems
Factorials, path counts, and combinatorics generate enormous intermediate values fast. 20! is about 2.4 × 10¹⁸, which still fits in Int. 21! doesn't. When a problem says "return the answer modulo 10⁹ + 7," that's the problem telling you the actual answer doesn't fit anywhere, apply the mod after every multiplication:
let MOD = 1_000_000_007 func multiplyMod(_ a: Int, _ b: Int) -> Int { return ((a % MOD) * (b % MOD)) % MOD }
Apply this inside the loop, not just at the end. a * b can overflow before you get to the % MOD. The mod at the end is too late to help.
Prefix Sum Arrays
A prefix sum over 10⁵ elements each up to 10⁹ reaches 10¹⁴, fine for Int. If elements can reach 10¹⁸ and the array is long, the sum overflows. Always check the constraint block before assuming prefix sums are safe.
Binary Search on an Answer Range
Problems like "Koko Eating Bananas" or "Minimum Capacity to Ship" binary-search over a computed range whose upper bound can hit the billions. The midpoint is safe with lo + (hi - lo) / 2. The bigger risk is the validity check inside the loop: multiplying the candidate by a count, for example. Confirm those intermediate products stay within bounds.
Narrowing Conversions Trap Too
Swift doesn't do implicit numeric conversions. You always spell them out:
let x: Int = 42 let y: Double = Double(x) // fine let z: Int32 = Int32(x) // crashes if x > 2,147,483,647
Narrowing conversions trap if the value doesn't fit. Same crash-on-overflow principle, applied to type coercion. Swift is not going to quietly drop your bits for you.
Use exactly: when you want an optional instead of a fatal error:
let big: Int = 3_000_000_000 let narrow = Int32(exactly: big) // nil, no crash
In interview code you typically control your types, so this comes up less often. But if a problem hands you data from an external source or asks you to cast to a smaller type, exactly: is the safe path.
Quick Reference
| Situation | What to write |
|---|---|
| Binary search midpoint | lo + (hi - lo) / 2 |
| Initialize min tracker | var best = Int.max |
| Initialize max tracker | var best = Int.min |
| Intentional wrapping | a &+ b, a &- b, a &* b |
| Detect overflow without crashing | .addingReportingOverflow(_:) |
| Counting problems with mod | ((a % MOD) * (b % MOD)) % MOD |
| Safe narrowing cast | Int32(exactly: x) ?? fallback |
Guard Int.min / -1 | Check b != -1 || a != Int.min |
If you want to practice catching these bugs under realistic pressure, SpaceComplexity runs voice-based mock DSA interviews with rubric feedback, so you find out whether you'd actually spot the overflow before it costs you the offer.
For more Swift-specific interview patterns, the Swift coding interview gotchas guide covers several more footguns beyond overflow. The int32 vs int64 guide shows how overflow plays out across languages. The Swift interview idioms guide has patterns for writing cleaner code faster in a timed setting.
Further Reading
- Swift Language Reference: Integers, official docs on types, literals, and bounds
- Swift Standard Library: Overflow Operators,
&+,&-,&*reference - Swift Standard Library: FixedWidthInteger, the protocol behind
addingReportingOverflowand friends - Wikipedia: Integer overflow, historical context and cross-language comparison
- Wikipedia: Two's complement, the representation that makes wrapping deterministic