# Swift Arithmetic Operators

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

In Swift, arithmetic operators are used to perform basic mathematical operations on numeric types like `Int`, `Double`, and `Float`. Below, I’ll explain the core arithmetic operators in Swift, their functionality, and provide clear examples for each. I'll keep it concise yet comprehensive, focusing on the basics for beginners.

## Arithmetic Operators in Swift

Swift supports the following arithmetic operators:

1. **Addition (`+`)**
2. **Subtraction (`-`)**
3. **Multiplication (`*`)**
4. **Division (`/`)**
5. **Modulus (`%`)**
6. **Increment (`+=`) and Decrement (`-=`) (Compound Assignment)**

> **Type Safety:** Operators work only with compatible types (e.g., you can’t add an `Int` to a `Double` without explicit conversion).

## 1. Addition (`+`)

Adds two numbers or concatenates strings (though string concatenation is not arithmetic, it’s worth noting).

```swift
let a = 10
let b = 5
let sum = a + b
print(sum) // Output: 15

// Works with floating-point numbers
let x = 2.5
let y = 3.7
let result = x + y
print(result) // Output: 6.2
```

Output (tested with Swift 6.4):

```text
15
6.2
```

## 2. Subtraction (`-`)

Subtracts one number from another.

```swift
let c = 20
let d = 7
let difference = c - d
print(difference) // Output: 13

// Works with negative numbers
let p = 5.0
let q = 8.0
let result = p - q
print(result) // Output: -3.0
```

Output (tested with Swift 6.4):

```text
13
-3.0
```

## 3. Multiplication (`*`)

Multiplies two numbers.

```swift
let e = 6
let f = 4
let product = e * f
print(product) // Output: 24

// Works with floating-point numbers
let r = 2.5
let s = 3.0
let result = r * s
print(result) // Output: 7.5
```

Output (tested with Swift 6.4):

```text
24
7.5
```

## 4. Division (`/`)

Divides one number by another. For integers, division truncates to an integer (no decimal part). For floating-point numbers, it retains the decimal.

```swift
let g = 15
let h = 4
let quotient = g / h
print(quotient) // Output: 3 (integer division truncates)

// Floating-point division
let m = 15.0
let n = 4.0
let result = m / n
print(result) // Output: 3.75
```

Output (tested with Swift 6.4):

```text
3
3.75
```

**Note:** Division by zero will cause a runtime error in Swift, so ensure the denominator is non-zero.

## 5. Modulus (`%`)

Returns the remainder of division. Works only with integers in Swift.

```swift
let i = 17
let j = 5
let remainder = i % j
print(remainder) // Output: 2 (17 ÷ 5 = 3 remainder 2)

// Another example
let k = 10
let l = 3
print(k % l) // Output: 1
```

Output (tested with Swift 6.4):

```text
2
1
```

**Note:** Modulus does not work with `Double` or `Float` directly. For floating-point remainders, use the `truncatingRemainder(dividingBy:)` method:

```swift
let x = 10.5
let y = 3.0
let remainder = x.truncatingRemainder(dividingBy: y)
print(remainder) // Output: 1.5
```

Output (tested with Swift 6.4):

```text
1.5
```

## 6. Compound Assignment Operators (`+=`, `-=`, `*=`, `/=`, `%=`)

These combine an arithmetic operation with assignment, modifying a variable in place.

```swift
var number = 10
number += 5 // Equivalent to number = number + 5
print(number) // Output: 15

number -= 3 // Equivalent to number = number - 3
print(number) // Output: 12

number *= 2 // Equivalent to number = number * 2
print(number) // Output: 24

number /= 4 // Equivalent to number = number / 4
print(number) // Output: 6

number %= 5 // Equivalent to number = number % 5
print(number) // Output: 1
```

Output (tested with Swift 6.4):

```text
15
12
24
6
1
```

## Key Points

- **Type Safety:** You cannot mix types (e.g., `Int` and `Double`) without conversion. Use type casting like `Double(a)` or `Int(x)` when needed.

```swift
let intValue = 10
let doubleValue = 5.5
let result = Double(intValue) + doubleValue // Convert int to double
print(result) // Output: 15.5
```

Output (tested with Swift 6.4):

```text
15.5
```

- **Operator Precedence:** Swift follows standard mathematical precedence (e.g., `*` and `/` before `+` and `-`). Use parentheses to override.

```swift
let result = 10 + 5 * 2
print(result) // Output: 20 (5 * 2 = 10, then 10 + 10)

let explicit = (10 + 5) * 2
print(explicit) // Output: 30 (10 + 5 = 15, then 15 * 2)
```

Output (tested with Swift 6.4):

```text
20
30
```

- **Overflow Handling:** Swift’s arithmetic operators are safe by default and will throw an error on overflow (e.g., exceeding `Int.max`). Use overflow operators (`&+`, `&-`, `&*`) for wraparound behavior if needed.

```swift
var maxInt = Int.max
// maxInt += 1 // This would cause a runtime error
maxInt &+= 1 // Overflow wraps around
print(maxInt) // Output: Int.min (wraps to negative)
```

Output (tested with Swift 6.4):

```text
-9223372036854775808
```

## Practical Example Combining Operators

Here’s a simple Swift program that uses multiple arithmetic operators to calculate the total cost of items with a discount:

```swift
let pricePerItem = 25.0
let quantity = 3
let discount = 10.0

// Calculate subtotal
let subtotal = pricePerItem * Double(quantity)
print("Subtotal: \(subtotal)") // Output: Subtotal: 75.0

// Apply discount
let total = subtotal - discount
print("Total after discount: \(total)") // Output: Total after discount: 65.0

// Calculate items per dollar
let itemsPerDollar = Double(quantity) / total
print("Items per dollar: \(itemsPerDollar)") // Output: Items per dollar: 0.046153846153846156
```

Output (tested with Swift 6.4):

```text
Subtotal: 75.0
Total after discount: 65.0
Items per dollar: 0.046153846153846156
```

## Best Practices

1. Use Explicit Type Annotations for Clarity
 Swift’s type inference is powerful, but explicitly declaring types for numeric variables improves readability and avoids unexpected type issues.
 

@@BLOCK11@@
2. Choose Appropriate Numeric Types
 Use `Int` for whole numbers and `Double` or `Float` for decimals, depending on precision needs. Prefer `Double` for better precision unless memory is a constraint.
 

@@BLOCK12@@
3. Leverage Compound Assignment for Conciseness
 

@@BLOCK13@@
4. Use Parentheses for Operator Precedence
 

@@BLOCK14@@
5. Handle Floating-Point Precision Carefully
 Floating-point arithmetic (`Double`, `Float`) can lead to small precision errors. Use `rounded()` or format output for user-facing displays.
 

@@BLOCK15@@
6. Validate Inputs Before Division
 

@@BLOCK16@@

## Limitations

1. Type Safety Restrictions
 

@@BLOCK17@@
2. Integer Division Truncation
 

@@BLOCK18@@

@@BLOCK19@@
3. Modulus Limited to Integers
 

@@BLOCK20@@
4. Overflow Safety
 

@@BLOCK21@@
5. No Built-In Unary Increment/Decrement
 

@@BLOCK22@@

## Practical Example Applying Best Practices

Here’s a Swift function that calculates a discounted price, incorporating best practices and avoiding common pitfalls:

```swift
func calculateDiscountedPrice(basePrice: Double, discountPercent: Double) -> Double? {
    // Validate inputs
    guard basePrice >= 0, discountPercent >= 0, discountPercent <= 100 else {
        print("Error: Invalid price or discount")
        return nil
    }
    
    // Ensure precise calculation
    let discountFraction = discountPercent / 100.0
    let discountedPrice = basePrice * (1.0 - discountFraction)
    
    // Round for display precision
    return discountedPrice.rounded(toPlaces: 2)
}

let price: Double = 99.99
let discount: Double = 20.0
if let finalPrice = calculateDiscountedPrice(basePrice: price, discountPercent: discount) {
    print("Final price: \(String(format: "%.2f", finalPrice))")
} else {
    print("Calculation failed")
}
// Output: Final price: 79.99
```

## Practice Exercise: Arithmetic Operators in Swift

**Instructions for the Student:** 

You're running a simple coffee shop app in Swift. Use what you've learned about constants (`let`), variables (`var`), basic data types like `Int` and `Double`, type inference, type annotation, literals, and comments to calculate the total cost of a customer's order. Focus on practicing arithmetic operators (`+`, `-`, `*`, `/`, `%`, and compound ones like `+=`) while handling prices and quantities. Remember to validate for division by zero and use parentheses for clarity. Write your code in a Swift Playground or Xcode file.

**Question:** 

A customer orders 3 lattes at $4.50 each, plus 2 espressos at $2.75 each. Apply a 10% discount on the subtotal, then add a flat $1.25 tax. Finally, calculate how many whole cents are left after rounding down the total to the nearest dollar (use modulus `%` for the remainder).

- Declare constants for the prices (use `Double` with type annotation).
- Use variables to track subtotal, discount, tax, and final total (start with type inference where possible).
- Use compound operators to update the subtotal and total.
- Add comments explaining each arithmetic step.
- Print the subtotal, final total, and the cents remainder (e.g., "Cents left: X").

**Expected Output:**

```swift
Subtotal: 19.0
Final total: 18.35
Cents left: 35
```

**Hint:** For the discount, calculate it as `subtotal * 0.10`. For rounding down to the nearest dollar, use integer division after converting to cents (multiply total by 100, then `/` and `%` with 100).

## Solution

```swift
// Constants for prices with type annotation
let lattePrice: Double = 4.50
let espressoPrice: Double = 2.75

// Variables for quantities (type inference to Int)
var latteQuantity = 3
var espressoQuantity = 2

// Calculate subtotal using multiplication and addition
var subtotal = lattePrice * Double(latteQuantity) + espressoPrice * Double(espressoQuantity)
print("Subtotal: \(subtotal)") // Output: Subtotal: 19.0

// Apply 10% discount using multiplication (convert percent to fraction)
let discountPercent: Double = 0.10
var discountedSubtotal = subtotal - (subtotal * discountPercent) // Or use: subtotal *= (1 - discountPercent)

// Add tax using addition
let tax: Double = 1.25
discountedSubtotal += tax // Compound assignment for concise update
print("Final total: \(discountedSubtotal)") // Output: Final total: 18.35

// Calculate cents remainder: Convert to cents, then use modulus
let totalInCents: Int = Int(discountedSubtotal * 100) // 1835 cents
let dollars = totalInCents / 100 // Integer division truncates to whole dollars
let centsRemainder = totalInCents % 100 // Modulus for remainder
print("Cents left: \(centsRemainder)") // Output: Cents left: 35

// Note: No division by zero here, but in real code, guard against quantity == 0 for per-item calcs
```

Output (tested with Swift 6.4):

```text
Subtotal: 19.0
Final total: 18.35
Cents left: 35
```
