# Swift Overflow Operators &+, &-, &*: Wrapping Arithmetic Explained

Source: https://devdocs10.com/articles/swift/swift-overflow-operators  
By Murat Bo · Updated 2026-10-28 · DevDocs10 (https://devdocs10.com)

Swift's overflow operators `&+`, `&-` and `&*` do integer arithmetic that wraps around instead of stopping the program: `UInt8(255) &+ 1` is 0, and `Int8(127) &+ 1` is -128. The ordinary operators `+`, `-` and `*` check every result, and when it does not fit the type they trap with an arithmetic overflow, in debug and release builds alike. Use the `&` versions only when wrapping is the behavior you want, as in hash functions, checksums and rolling counters, and use `addingReportingOverflow(_:)` when you need to know that an overflow happened. Below: what the trap looks like, how wrapping works bit by bit, real uses, the reporting methods, and the edge cases such as division, negation and `-Ounchecked`.

> **Difficulty:** Intermediate
>
> **Helpful to know first:** Swift integer types such as Int, UInt8 and Int8, their minimum and maximum values, and basic arithmetic operators.

## Why 250 + 10 Stops a Swift Program

Every Swift integer type has a fixed size. A `UInt8` holds 0 to 255, an `Int8` holds -128 to 127, and `Int` on a 64-bit platform holds about ±9.2 quintillion. When the true result of `+`, `-` or `*` is outside that range, Swift does not hand you a wrong number. It stops the program at that line.

```swift
func addPoints(_ score: UInt8, _ bonus: UInt8) -> UInt8 {
    score + bonus
}

print(addPoints(200, 50))   // Output: 250
print(addPoints(250, 10))   // 260 does not fit: the program stops here
```

Built with `swiftc` and run in Terminal, the program prints 250 and then dies. There is no "Fatal error" line. The shell only reports the signal: zsh prints `zsh: trace trap ./main`, bash prints `Trace/BPT trap: 5`, and the exit status is 133. In Xcode the debugger stops on the `score + bonus` line with `Thread 1: Swift runtime failure: arithmetic overflow`, and a crash report names the same frame, `Swift runtime failure: arithmetic overflow`. How to read that crash in the debugger is covered in [debugging Swift in Xcode](/articles/swift/swift-debugging-xcode).

When both values are known while compiling, the error comes even earlier. `let big = Int.max + 1` does not build: `arithmetic operation '9223372036854775807 + 1' (on type 'Int') results in an overflow`.

The overflow operators remove the check and keep the low bits of the result instead:

```swift
let highest: UInt8 = 255
let lowest: UInt8 = 0

print(highest &+ 1)   // Output: 0
print(lowest &- 1)    // Output: 255
print(highest &* 2)   // Output: 254
```

Output (tested with Swift 6.4):

```text
0
255
254
```

The design is deliberate. An overflow in ordinary code is almost always a bug, such as a count that grew too far or a size computed from bad input, and a crash at the exact line is easier to find than a silently wrong value. When wrapping is part of the algorithm, the `&` prefix tells the compiler and every reader that it is intended.

## How Wrapping Works: Keeping Only the Bits That Fit

Wrapping arithmetic computes the exact result and then throws away every bit above the type's width. For an 8-bit type that is the same as taking the result modulo 256. For signed types the remaining bits are read as two's complement, so the value jumps from the maximum to the minimum.

| Expression | Exact result | Bits kept (8) | Wrapped value |
| --- | --- | --- | --- |
| `UInt8(250) &+ 10` | 260 | `0000_0100` | 4 |
| `UInt8(0) &- 1` | -1 | `1111_1111` | 255 |
| `UInt8(200) &* 2` | 400 | `1001_0000` | 144 |
| `Int8(127) &+ 1` | 128 | `1000_0000` | -128 |
| `Int8(-128) &- 1` | -129 | `0111_1111` | 127 |

The same rule holds for every width, so `Int.max &+ 1` equals `Int.min`. Each operator also has a compound form that updates a variable in place:

```swift
var level: UInt8 = 250

level &+= 10
print(level)   // Output: 4
level &-= 5
print(level)   // Output: 255
level &*= 3
print(level)   // Output: 253

print(Int8(127) &+ 1, Int.max &+ 1 == Int.min)   // Output: -128 true
```

Output (tested with Swift 6.4):

```text
4
255
253
-128 true
```

The last multiplication is 255 × 3 = 765, and 765 − 512 = 253. Wrapping is well defined for both signed and unsigned types. That is a real difference from C, where signed overflow is undefined behavior and the compiler may assume it never happens.

> There is no `&/` operator. Division can only overflow in one case, `Int.min / -1`, and the reporting method shown later handles it.

## Where Wrapping Arithmetic Is the Right Tool

Wrapping is correct whenever the algorithm is defined in terms of fixed-width machine arithmetic. These are the cases you will meet most often.

### A 32-bit FNV-1a string hash

Hash functions multiply by large constants on purpose and rely on the overflow to mix the bits. FNV-1a XORs in each byte and then multiplies by the FNV prime. With `*` instead of `&*`, the very first multiplication would stop the program.

```swift
func fnv1a(_ text: String) -> UInt32 {
    var hash: UInt32 = 0x811C_9DC5        // FNV offset basis
    for byte in text.utf8 {
        hash ^= UInt32(byte)
        hash = hash &* 0x0100_0193        // FNV prime, wraps on purpose
    }
    return hash
}

print(String(fnv1a("a"), radix: 16))        // Output: e40c292c
print(String(fnv1a("foobar"), radix: 16))   // Output: bf9cf968
```

Output (tested with Swift 6.4):

```text
e40c292c
bf9cf968
```

Both results match the published FNV-1a test values, which only works because `&*` wraps exactly the way the reference C implementation does with `uint32_t`. The `^=` is bitwise XOR, explained in [Swift bitwise and shift operators](/articles/swift/swift-bitwise-shift).

### An 8-bit checksum for a data packet

Many file formats and serial protocols, Intel HEX among them, add up all bytes modulo 256 and append the two's complement of that sum. A receiver adds every byte, including the checksum, and expects exactly 0.

```swift
func checksum(_ bytes: [UInt8]) -> UInt8 {
    let sum = bytes.reduce(0, &+)   // the operator itself as the combine function
    return 0 &- sum                  // two's complement of the sum
}

let packet: [UInt8] = [0x10, 0xF0, 0x7A, 0xC3]
let check = checksum(packet)
print(check)                          // Output: 195

let total = (packet + [check]).reduce(0, &+)
print(total)                          // Output: 0
```

Output (tested with Swift 6.4):

```text
195
0
```

The sum of the four bytes is 573, which wraps to 61. `0 &- 61` is 195, and 61 + 195 = 256, which wraps back to 0. Passing `&+` directly to `reduce` works because Swift operators are functions.

### Sequence numbers that roll over

Network protocols and game servers number their messages with a fixed-size counter that is expected to roll over. Wrapping subtraction then gives the distance between two numbers even across the rollover.

```swift
var frame: UInt16 = 65_534
for _ in 1...3 {
    frame &+= 1
    print(frame)
}
// Output:
// 65535
// 0
// 1

let sent: UInt16 = 65_530
let received: UInt16 = 4
print(received &- sent)   // Output: 10
```

Output (tested with Swift 6.4):

```text
65535
0
1
10
```

Frame 4 arrived 10 frames after frame 65,530, although 4 is the smaller number. Plain `-` would trap here, because `4 - 65530` is negative and a `UInt16` cannot hold that.

## Detecting Overflow Instead of Wrapping: addingReportingOverflow

Sometimes neither a crash nor a wrapped value is acceptable. Input from a file or a network can be anything, and you want to reject it. Every fixed-width integer has methods that return the wrapped result together with a `Bool` that tells you whether it overflowed.

```swift
func bufferSize(width: Int, height: Int, bytesPerPixel: Int) -> Int? {
    let (pixels, overflow1) = width.multipliedReportingOverflow(by: height)
    let (bytes, overflow2) = pixels.multipliedReportingOverflow(by: bytesPerPixel)
    return overflow1 || overflow2 ? nil : bytes
}

print(bufferSize(width: 4000, height: 3000, bytesPerPixel: 4) as Any)
// Output: Optional(48000000)
print(bufferSize(width: 1 << 32, height: 1 << 31, bytesPerPixel: 4) as Any)
// Output: nil
```

Output (tested with Swift 6.4):

```text
Optional(48000000)
nil
```

The tuple has the labels `partialValue` and `overflow`; here it is taken apart into two constants. An image header that claims 232 × 231 pixels now gives `nil` instead of crashing the app or allocating a wrapped, far too small buffer.

| You need | Use | Example |
| --- | --- | --- |
| The wrapped result, no check | `&+`, `&-`, `&*` | `UInt8(250) &+ 10` is 4 |
| The wrapped result and an overflow flag | `addingReportingOverflow(_:)`, `subtractingReportingOverflow(_:)`, `multipliedReportingOverflow(by:)`, `dividedReportingOverflow(by:)`, `remainderReportingOverflow(dividingBy:)` | `UInt8(250).addingReportingOverflow(10)` is `(partialValue: 4, overflow: true)` |
| The exact product of two large numbers | `multipliedFullWidth(by:)` | `Int.max.multipliedFullWidth(by: 2)` is `(high: 0, low: 18446744073709551614)` |
| A conversion that keeps the low bits | `init(truncatingIfNeeded:)` | `UInt8(truncatingIfNeeded: 300)` is 44 |
| A conversion that stops at the limit | `init(clamping:)` | `UInt8(clamping: 300)` is 255 |
| A conversion that fails softly | `init(exactly:)` | `UInt8(exactly: 300)` is `nil` |

The conversions matter because a plain `UInt8(300)` also traps. Unlike arithmetic overflow, a debug build prints a message first, `Fatal error: Not enough bits to represent the passed value`; an optimized (`-O`) build stops without it.

## How Overflow Checking Behaves in Detail

### Debug and release builds both trap

Many developers expect release builds to drop the check, as release builds drop `assert`. They do not. A program built with `-Onone` (Xcode's Debug configuration) and one built with `-O` (Release) both stop on overflow. The check is cheap, usually one extra branch per operation, and the optimizer removes it wherever it can prove the result fits. For how `assert` and `precondition` differ between builds, see [Swift assertions](/articles/swift/swift-assertions).

### What -Ounchecked changes

The `-Ounchecked` optimization mode removes the overflow checks along with other runtime safety checks. An overflowing `+` then no longer stops the program, and it continues with whatever value the machine produced, which is often the wrapped value. Swift documents this mode as removing safety checks, not as switching `+` to wrapping arithmetic, so an overflow there is still a bug whose effects you cannot rely on. If you want wrapping, write `&+`; it behaves the same in every build mode.

### Division, remainder, and negation can overflow too

The signed minimum has no positive partner: `Int8` goes down to -128 but only up to 127. So negating -128, taking its `abs`, or dividing it by -1 cannot produce a valid `Int8`, and all three trap. In a debug build, division prints `Fatal error: Division results in an overflow` and the remainder prints `Fatal error: Division results in an overflow in remainder operation`; negation and `abs` trap without a message, like `+`. Dividing by zero is a separate trap, reported as `Fatal error: Division by zero`.

```swift
let values: [Int8] = [-128, 7]
for value in values {
    print(value.dividedReportingOverflow(by: -1))
}
// Output:
// (partialValue: -128, overflow: true)
// (partialValue: -7, overflow: false)

print(0 &- Int8.min)   // Output: -128
```

Output (tested with Swift 6.4):

```text
(partialValue: -128, overflow: true)
(partialValue: -7, overflow: false)
-128
```

`0 &- x` is the wrapping way to negate. For the one value that overflows it returns the value unchanged.

### Shifts never trap; &<< and &>> wrap the shift amount

`<<` and `>>` are not checked for overflow at all: bits that move out are simply lost, so `Int8(100) << 1` is -56. The masking shifts `&<<` and `&>>` belong to the same "& means no checks" family, but what they wrap is the shift amount: `UInt8(1) &<< 9` is 2, because 9 is reduced to 1. Both are covered in [Swift bitwise and shift operators](/articles/swift/swift-bitwise-shift).

### Floating-point numbers do not trap

`Double` and `Float` follow IEEE 754: a result that is too large becomes infinity, so `Double.greatestFiniteMagnitude * 2` is `inf`. The overflow operators do not exist for them. There is no difference between the Swift 5 and Swift 6 language modes in any of this.

## Predict the Output

Snippet 1. What does this print?

```swift
let a: UInt8 = 200
let b: UInt8 = 100

print(a &+ b, a &- b, b &- a)
```

Output (tested with Swift 6.4):

```text
44 100 156
```

**Answer:**

It prints `44 100 156`.

200 + 100 = 300, and 300 − 256 = 44. 200 − 100 = 100 fits, so nothing wraps. 100 − 200 = −100, and −100 + 256 = 156. Wrapping only changes a result that falls outside 0...255.

Snippet 2. What does this print?

```swift
let x: Int8 = -128

print(x &* -1, x &- 1)
print(x.addingReportingOverflow(-1))
```

Output (tested with Swift 6.4):

```text
-128 127
(partialValue: 127, overflow: true)
```

**Answer:**

It prints `-128 127` and then `(partialValue: 127, overflow: true)`.

The exact result of -128 × -1 is 128, one more than `Int8.max`, which wraps back to -128. -128 − 1 wraps to the top of the range, 127. The reporting method gives the same wrapped value as `&+` would, and adds `overflow: true`.

## Common Mistakes with Swift Overflow Operators

### Using &+ to make a crash go away

When a counter traps, it is tempting to switch to `&+` so the crash disappears. The bug does not disappear; it turns into wrong data.

**Problem:** The ticket count wraps from 255 to 0. The app keeps running and reports that no tickets were sold, which is worse than a crash because nobody notices.

```swift
var ticketsSold: UInt8 = 255
ticketsSold = ticketsSold &+ 1
print(ticketsSold)   // Output: 0
```

Output (tested with Swift 6.4):

```text
0
```

**Fix:** Use `Int` for counts and keep the checked operator.

```swift
var ticketsSold = 255
ticketsSold += 1
print(ticketsSold)   // Output: 256
```

Output (tested with Swift 6.4):

```text
256
```

The corrected version works because `Int` has room for any realistic count, and the checked `+=` still stops the program if a bug ever pushes it past `Int.max`.

### Wrapping in the narrow type before widening

Averaging two bytes looks like a natural place for `&+`, because `+` traps on 200 + 100.

**Problem:** The sum 300 wraps to 44 before the division, so the average of 200 and 100 comes out as 22.

```swift
let left: UInt8 = 200
let right: UInt8 = 100

let average = (left &+ right) / 2
print(average)   // Output: 22
```

Output (tested with Swift 6.4):

```text
22
```

**Fix:** Widen first, add in the wider type, then narrow the result, which always fits.

```swift
let left: UInt8 = 200
let right: UInt8 = 100

let average = UInt8((UInt16(left) + UInt16(right)) / 2)
print(average)   // Output: 150
```

Output (tested with Swift 6.4):

```text
150
```

The corrected version works because a `UInt16` can hold any sum of two bytes, and the average of two bytes is always back in byte range.

### Narrowing a hash with UInt8(_:)

Hash code often ends by reducing a wide value to a small one, for example to choose one of 256 buckets.

**Problem:** `UInt8(hash)` is a checked conversion. For almost every hash value it stops the program; a debug build reports `Fatal error: Not enough bits to represent the passed value`.

```swift
func bucket(for hash: UInt32) -> UInt8 {
    UInt8(hash)
}

print(bucket(for: 0x811C_9DC5))
```

**Fix:** Use the truncating conversion, the conversion counterpart of the overflow operators.

```swift
func bucket(for hash: UInt32) -> UInt8 {
    UInt8(truncatingIfNeeded: hash)
}

print(bucket(for: 0x811C_9DC5))   // Output: 197
```

Output (tested with Swift 6.4):

```text
197
```

The corrected version works because `truncatingIfNeeded:` keeps the low 8 bits (`0xC5`, which is 197) without any range check.

### Expecting &+ to work on Double

The overflow operators are defined only for integer types.

**Problem:** The compiler rejects this with `binary operator '&+' cannot be applied to two 'Double' operands`.

```swift
let price = 1.5
print(price &+ 1.0)
```

**Fix:** Use ordinary `+`; floating-point types never trap on overflow.

```swift
let price = 1.5
print(price + 1.0)                         // Output: 2.5
print(Double.greatestFiniteMagnitude * 2)  // Output: inf
```

Output (tested with Swift 6.4):

```text
2.5
inf
```

The corrected version works because `Double` arithmetic already saturates to infinity instead of trapping.

## Find the Bug

This djb2 hash picks a cache file name. It worked in a quick test with a short name. What happens with the second call?

```swift
func djb2(_ text: String) -> UInt64 {
    var hash: UInt64 = 5381
    for byte in text.utf8 {
        hash = hash * 33 + UInt64(byte)
    }
    return hash
}

print(djb2("logo.png"))
print(djb2("profile-photo-2026.jpg"))
```

**Answer:**

The first call prints `7572635083902409`. The second call stops the program with an arithmetic overflow. Each step multiplies the hash by 33, so after about a dozen bytes the value no longer fits in 64 bits, and the checked `*` traps. Short test strings hide the problem.

djb2, like most hash functions, is defined with wrapping arithmetic. Use the overflow operators:

```swift
func djb2(_ text: String) -> UInt64 {
    var hash: UInt64 = 5381
    for byte in text.utf8 {
        hash = hash &* 33 &+ UInt64(byte)
    }
    return hash
}

print(djb2("logo.png"))                 // Output: 7572635083902409
print(djb2("profile-photo-2026.jpg"))   // Output: 16724076202637667091
```

Output (tested with Swift 6.4):

```text
7572635083902409
16724076202637667091
```

The short input gives the same hash as before, because no step overflowed. Long inputs now wrap the way the algorithm expects.

## Choosing Between +, &+, and the Reporting Methods

| Situation | Use |
| --- | --- |
| Counts, money in cents, indexes, sizes: ordinary app logic | `+`, `-`, `*`, and let an overflow trap |
| Hashes, checksums, random number generators, rolling sequence numbers, emulated hardware registers | `&+`, `&-`, `&*` |
| Untrusted input where overflow is possible and must be rejected | `addingReportingOverflow(_:)` and its siblings |
| The exact value of a large product | `multipliedFullWidth(by:)` or a wider type |
| A value that should stop at the limit | `init(clamping:)` or a small saturating helper |

If you are unsure, use the ordinary operator. A trap is easy to notice and fix; a wrapped value can travel through the program for a long time before anyone sees it. The integer types and their ranges are listed in [Swift data types](/articles/swift/swift-data-types), and the ordinary operators in [Swift arithmetic operators](/articles/swift/swift-operators-arithmetic).

## Interview Questions About Integer Overflow in Swift

### What happens when an Int overflows in Swift?

With `+`, `-` or `*` the program traps at runtime, in both debug and release builds. If both operands are compile-time constants, the compiler reports the overflow as an error instead. To get a wrapped result, use `&+`, `&-` or `&*`.

### How is &+ different from addingReportingOverflow(_:)?

Both produce the same wrapped value. `&+` returns only that value; `addingReportingOverflow(_:)` returns a tuple `(partialValue:overflow:)`, so the caller can react to the overflow.

### Is signed overflow undefined behavior in Swift, as in C?

No. In normal builds it is a guaranteed trap, and with the overflow operators it is guaranteed two's complement wrapping. The only exception is `-Ounchecked`, which removes the checks and with them the guarantee.

## Try It Yourself

Audio and image code often needs saturating arithmetic: a sum that is too large stops at the maximum instead of wrapping or trapping.

- Write `saturatingAdd(_:_:)` that adds two `Int8` values.
- Use `addingReportingOverflow(_:)` to detect overflow.
- On overflow return `Int8.max` or `Int8.min`, depending on the direction.
- Print the results for (100, 100), (-100, -100), (50, 20) and (-128, 127).

**Expected output:** `127`, `-128`, `70` and `-1`, one per line.

**Hint:** Adding two numbers can only overflow when both have the same sign, so the sign of the second number tells you which limit you passed.

**Solution:**

```swift
func saturatingAdd(_ a: Int8, _ b: Int8) -> Int8 {
    let (sum, overflow) = a.addingReportingOverflow(b)
    guard overflow else { return sum }
    return b > 0 ? .max : .min
}

print(saturatingAdd(100, 100))    // Output: 127
print(saturatingAdd(-100, -100))  // Output: -128
print(saturatingAdd(50, 20))      // Output: 70
print(saturatingAdd(-128, 127))   // Output: -1
```

Output (tested with Swift 6.4):

```text
127
-128
70
-1
```

## Summary

- `+`, `-` and `*` trap on overflow in debug and release builds; Xcode shows `Swift runtime failure: arithmetic overflow`, and constant expressions fail at compile time.
- `&+`, `&-` and `&*` (and `&+=`, `&-=`, `&*=`) keep the low bits of the result: modulo 2bitWidth, read as two's complement for signed types.
- Use wrapping only where the algorithm needs it: hashes, checksums, rolling counters, random number generators.
- `addingReportingOverflow(_:)` and its siblings return the wrapped value plus an `overflow` flag; `init(truncatingIfNeeded:)`, `init(clamping:)` and `init(exactly:)` are the matching conversions.
- Division, remainder, negation and `abs` of the signed minimum also trap; there is no `&/`.
- `-Ounchecked` removes the checks but does not promise wrapping; write `&+` when you mean it.

Wrapping arithmetic and bit operations usually appear together. Next, read [Swift bitwise and shift operators](/articles/swift/swift-bitwise-shift) to see how XOR, masks and shifts complete hash and checksum code.
