Swift Arithmetic Operators

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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
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 · Swift 6.4
-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 · Swift 6.4
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.

    Swift
    let price: Double = 19.99
    let quantity: Int = 3
    let total = price * Double(quantity) // Explicit conversion
    print(total) // Output: 59.97
    Output✓ Tested · Swift 6.4
    59.97
  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.

    Swift
    let distance: Double = 42.195 // Marathon distance in km, Double for precision
    let laps: Int = 10 // Whole number, no need for decimal
  3. Leverage Compound Assignment for Conciseness

    Swift
    var score = 100
    score += 10 // Cleaner than score = score + 10
    print(score) // Output: 110
    Output✓ Tested · Swift 6.4
    110
  4. Use Parentheses for Operator Precedence

    Swift
    let result = (10 + 5) * 2 // Clear intent
    print(result) // Output: 30
    Output✓ Tested · Swift 6.4
    30
  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.

    Swift
    let a = 0.1
    let b = 0.2
    let sum = (a + b).rounded(toPlaces: 2) // Avoids 0.30000000000000004
    print(sum) // Output: 0.3
    
    extension Double {
        func rounded(toPlaces places: Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
    }
    Output✓ Tested · Swift 6.4
    0.3
  6. Validate Inputs Before Division

    Swift
    func divide(_ numerator: Int, by denominator: Int) {
        if denominator != 0 {
            let result = numerator / denominator
            print(result)
        } else {
            print("Error: Division by zero")
        }
    }
    
    divide(10, by: 0)
    // Output: Error: Division by zero
    Output✓ Tested · Swift 6.4
    Error: Division by zero

Limitations

  1. Type Safety Restrictions

    Swift
    let intVal = 5
    let doubleVal = 2.5
    let result = Double(intVal) + doubleVal // Convert Int to Double
    print(result) // Output: 7.5
    Output✓ Tested · Swift 6.4
    7.5
  2. Integer Division Truncation

    Swift
    let a = 7
    let b = 2
    print(a / b) // Output: 3 (not 3.5)
    Output✓ Tested · Swift 6.4
    3
    Swift
    print(Double(a) / Double(b)) // Output: 3.5
  3. Modulus Limited to Integers

    Swift
    let x = 10.5
    let y = 3.0
    let remainder = x.truncatingRemainder(dividingBy: y)
    print(remainder) // Output: 1.5
    Output✓ Tested · Swift 6.4
    1.5
  4. Overflow Safety

    Swift
    var maxInt = Int.max
    maxInt &+= 1 // Wraps around instead of crashing
    print(maxInt) // Output: Int.min
    Output✓ Tested · Swift 6.4
    -9223372036854775808
  5. No Built-In Unary Increment/Decrement

    Swift
    var counter = 0
    counter += 1 // Instead of counter++
    print(counter) // Output: 1
    Output✓ Tested · Swift 6.4
    1

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:

Show solution
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 · Swift 6.4
Subtotal: 19.0
Final total: 18.35
Cents left: 35