0
0
Swiftprogramming~5 mins

Arithmetic operators and overflow in Swift

Choose your learning style9 modes available
Introduction

Arithmetic operators let you do math like adding or multiplying numbers. Overflow happens when a number gets too big or too small for the space it has.

When you want to add, subtract, multiply, or divide numbers in your program.
When you need to handle very large or very small numbers safely.
When working with fixed-size numbers like bytes or integers that can overflow.
When you want to avoid your program crashing due to number overflow.
When you want to use special Swift operators that allow overflow intentionally.
Syntax
Swift
let sum = a + b
let difference = a - b
let product = a * b
let quotient = a / b

// Overflow operators
let overflowSum = a &+ b
let overflowDifference = a &- b
let overflowProduct = a &* b

Swift uses +, -, *, / for normal math operations.

Use &+, &-, &* to allow overflow without crashing.

Examples
Adds two numbers normally.
Swift
let a = 10
let b = 5
let sum = a + b
print(sum)
Uses &+ to add 1 to the max UInt8 value, causing overflow to 0.
Swift
let max = UInt8.max
let overflowSum = max &+ 1
print(overflowSum)
Normal + causes error on overflow, &+ allows wrapping around.
Swift
let max = UInt8.max
// let sum = max + 1 // This causes a runtime error
let safeSum = max &+ 1
print(safeSum)
Sample Program

This program shows normal max value for UInt8, then uses overflow operators &+ and &- to wrap around numbers instead of crashing.

Swift
import Foundation

let maxValue = UInt8.max
print("Max UInt8 value: \(maxValue)")

// Normal addition causes error if uncommented
// let errorSum = maxValue + 1

// Use overflow addition to wrap around
let wrappedSum = maxValue &+ 1
print("Wrapped sum with &+: \(wrappedSum)")

// Normal subtraction
let normalDiff = 10 - 3
print("Normal subtraction: \(normalDiff)")

// Overflow subtraction
let zero: UInt8 = 0
let wrappedDiff = zero &- 1
print("Wrapped subtraction with &-: \(wrappedDiff)")
OutputSuccess
Important Notes

Normal arithmetic operators in Swift will cause a runtime error if overflow happens.

Overflow operators (&+, &-, &*) let numbers wrap around like a clock.

Use overflow operators carefully to avoid unexpected bugs.

Summary

Arithmetic operators do math on numbers.

Overflow happens when numbers go beyond their limits.

Swift has special operators (&+, &-, &*) to allow overflow safely.