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:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Modulus (
%
) - 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).
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
2. Subtraction (-
)
Subtracts one number from another.
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
3. Multiplication (*
)
Multiplies two numbers.
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
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.
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
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.
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
Note: Modulus does not work with Double
or Float
directly. For floating-point remainders, use the truncatingRemainder(dividingBy:)
method:
let x = 10.5
let y = 3.0
let remainder = x.truncatingRemainder(dividingBy: y)
print(remainder) // Output: 1.5
6. Compound Assignment Operators (+=
, -=
, *=
, /=
, %=
)
These combine an arithmetic operation with assignment, modifying a variable in place.
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
Key Points
- Type Safety: You cannot mix types (e.g.,
Int
andDouble
) without conversion. Use type casting likeDouble(a)
orInt(x)
when needed.
let intValue = 10
let doubleValue = 5.5
let result = Double(intValue) + doubleValue // Convert int to double
print(result) // Output: 15.5
- Operator Precedence: Swift follows standard mathematical precedence (e.g.,
*
and/
before+
and-
). Use parentheses to override.
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)
- 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.
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)
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:
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
Best Practices
-
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.
let price: Double = 19.99 let quantity: Int = 3 let total = price * Double(quantity) // Explicit conversion print(total) // Output: 59.97
-
Choose Appropriate Numeric Types
Use
Int
for whole numbers andDouble
orFloat
for decimals, depending on precision needs. PreferDouble
for better precision unless memory is a constraint.let distance: Double = 42.195 // Marathon distance in km, Double for precision let laps: Int = 10 // Whole number, no need for decimal
-
Leverage Compound Assignment for Conciseness
var score = 100 score += 10 // Cleaner than score = score + 10 print(score) // Output: 110
-
Use Parentheses for Operator Precedence
let result = (10 + 5) * 2 // Clear intent print(result) // Output: 30
-
Handle Floating-Point Precision Carefully
Floating-point arithmetic (
Double
,Float
) can lead to small precision errors. Userounded()
or format output for user-facing displays.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 } }
-
Validate Inputs Before Division
let numerator = 10 let denominator = 0 if denominator != 0 { let result = numerator / denominator print(result) } else { print("Error: Division by zero") } // Output: Error: Division by zero
Limitations
-
Type Safety Restrictions
let intVal = 5 let doubleVal = 2.5 let result = Double(intVal) + doubleVal // Convert Int to Double print(result) // Output: 7.5
-
Integer Division Truncation
let a = 7 let b = 2 print(a / b) // Output: 3 (not 3.5)
print(Double(a) / Double(b)) // Output: 3.5
-
Modulus Limited to Integers
let x = 10.5 let y = 3.0 let remainder = x.truncatingRemainder(dividingBy: y) print(remainder) // Output: 1.5
-
Overflow Safety
var maxInt = Int.max maxInt &+= 1 // Wraps around instead of crashing print(maxInt) // Output: Int.min
-
No Built-In Unary Increment/Decrement
var counter = 0 counter += 1 // Instead of counter++ print(counter) // Output: 1
Practical Example Applying Best Practices
Here’s a Swift function that calculates a discounted price, incorporating best practices and avoiding common pitfalls:
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:
Subtotal: 19.5
Final total: 20.43
Cents left: 43
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
// 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.5
// 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: 20.43
// Calculate cents remainder: Convert to cents, then use modulus
let totalInCents: Int = Int(discountedSubtotal * 100) // 2043 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: 43
// Note: No division by zero here, but in real code, guard against quantity == 0 for per-item calcs