← All posts

How to use Swift's basic operators

Arthur C. Codex September 26, 2023

Every Swift developer needs to master operators—those special symbols and phrases that let you manipulate, compare, and combine values. Whether you're building your first iOS app or refactoring production code, understanding how operators work under the hood will make you a more confident programmer. Let's explore Swift's fundamental operators with practical examples you can use today.

How to use Swift's basic operators

Arithmetic Operators: The Building Blocks

Swift provides four standard arithmetic operators that work with all numeric types—Int, Double, Float, and even custom numeric types:

  • Addition (+) - Combines two values
  • Subtraction (-) - Finds the difference between values
  • Multiplication (*) - Multiplies values together
  • Division (/) - Divides one value by another

Here's how they work in practice:

let price = 100
let discount = 25
let quantity = 3

let finalPrice = price - discount  // 75
let totalCost = finalPrice * quantity  // 225
let perItemCost = totalCost / quantity  // 75

print("Total cost: \(totalCost)")  // Total cost: 225

Watch out for integer division: When dividing two integers, Swift returns an integer result by truncating any decimal places. If you need precise decimal results, use Double or Float types instead:

let intResult = 7 / 2  // 3 (decimal truncated)
let doubleResult = 7.0 / 2.0  // 3.5 (precise result)

The Remainder Operator: More Than Just Modulo

The remainder operator (%) calculates what's left over after division. While it's similar to the modulo operation in mathematics, Swift's implementation has some nuances worth understanding:

let totalMinutes = 127
let hours = totalMinutes / 60  // 2
let minutes = totalMinutes % 60  // 7

print("\(hours) hours and \(minutes) minutes")  // 2 hours and 7 minutes

The remainder operator works with negative numbers too, following the formula: a % b always takes the sign of a:

let positiveRemainder = 9 % 4   // 1
let negativeRemainder = -9 % 4  // -1
let mixedRemainder = 9 % -4     // 1

Real-world use case: The remainder operator is perfect for cycling through array indices, determining even/odd numbers, or implementing circular buffers:

let colors = ["red", "green", "blue"]
let index = 7

// Safely wrap around array bounds
let selectedColor = colors[index % colors.count]  // "green"

Compound Assignment Operators: Write Less, Do More

Compound assignment operators combine an operation with assignment in a single, readable expression. Instead of writing count = count + 1, you can write count += 1. Swift supports compound versions of all arithmetic operators:

Operator Example Equivalent To
+= a += 5 a = a + 5
-= a -= 3 a = a - 3
*= a *= 2 a = a * 2
/= a /= 4 a = a / 4
%= a %= 3 a = a % 3

These operators make accumulation patterns more concise:

var cartTotal = 0.0
var itemCount = 0

// Processing items
cartTotal += 29.99  // Add item price
itemCount += 1

cartTotal += 49.99
itemCount += 1

// Apply bulk discount
if itemCount > 1 {
    cartTotal *= 0.9  // 10% discount
}

print("Total: $\(cartTotal)")  // Total: $71.982

Comparison Operators: Making Decisions

Comparison operators evaluate relationships between values and return a Boolean result (true or false). Swift provides six comparison operators that work with any comparable type:

Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Here's how these operators control program flow in a practical scenario:

let userAge = 16
let requiredAge = 18
let hasParentalConsent = true

// Check eligibility with multiple conditions
if userAge >= requiredAge {
    print("Access granted")
} else if userAge < requiredAge && hasParentalConsent {
    print("Access granted with parental consent")
} else {
    print("Access denied")
}  // Prints: "Access granted with parental consent"

Comparing Strings and Tuples

Swift's comparison operators work with more than just numbers. You can compare strings lexicographically (dictionary order) and tuples element by element:

// String comparison (case-sensitive)
let name1 = "Alice"
let name2 = "Bob"
print(name1 < name2)  // true (alphabetical order)

// Tuple comparison (left to right)
let version1 = (2, 1, 3)
let version2 = (2, 1, 5)
print(version1 < version2)  // true (compares third element)

Operator Precedence: Order Matters

When you combine multiple operators in a single expression, Swift follows specific precedence rules—similar to the order of operations in mathematics:

let result = 2 + 3 * 4  // 14, not 20
// Multiplication happens first: 3 * 4 = 12, then 2 + 12 = 14

// Use parentheses to override precedence
let explicitResult = (2 + 3) * 4  // 20

Precedence hierarchy (highest to lowest):

Parentheses: ()
Multiplication & Division: * / %
Addition & Subtraction: + -
Comparison: < <= > >= == !=
Logical AND: &&
Logical OR: ||
Assignment: = += -= *= /= %=

Try It Yourself: Build a Simple Calculator

Put these operators together to create a basic calculator function that demonstrates all the concepts we've covered:

func calculate(operation: String, a: Double, b: Double) -> Double? {
    switch operation {
    case "+":
        return a + b
    case "-":
        return a - b
    case "*":
        return a * b
    case "/":
        guard b != 0 else {
            print("Error: Division by zero")
            return nil
        }
        return a / b
    case "%":
        guard b != 0 else {
            print("Error: Modulo by zero")
            return nil
        }
        return a.truncatingRemainder(dividingBy: b)
    default:
        print("Unknown operation: \(operation)")
        return nil
    }
}

// Test the calculator
if let result = calculate(operation: "+", a: 15, b: 7) {
    print("Result: \(result)")  // Result: 22.0
}

Performance Considerations

Most Swift operators are highly optimized, but there are a few things to keep in mind when writing performance-critical code:

  • Integer operations are faster than floating-point operations—use Int when you don't need decimals
  • Compound assignment operators can be more efficient than their expanded forms because they avoid creating temporary copies
  • Division and modulo are slower than multiplication and addition—consider alternative algorithms when processing large datasets

These operators form the foundation of Swift programming. Whether you're hiring Swift developers or building your own projects, mastering these basics will make complex operations feel natural. Practice combining operators in different ways, experiment with edge cases, and pay attention to type safety—Swift's compiler will guide you toward correct solutions.

Next steps: Try creating functions that combine multiple operators, experiment with custom types that support these operators, and explore Swift's advanced operators like bitwise operations and overflow operators when you're ready to level up.