SWIFT
Swift Operator: Syntax, Usage, and Examples
A Swift operator performs a calculation, comparison, or logical check between values. Operators make your code expressive and concise, and they’re everywhere—whether you’re adding numbers, checking conditions, or combining strings.
How to Use Operators in Swift
Swift offers several categories of operators, each with its own syntax and purpose. You’ll use them in almost every line of Swift code.
Arithmetic Operators
These work on numbers:
let sum = 3 + 2 // 5
let difference = 7 - 4 // 3
let product = 6 * 2 // 12
let quotient = 10 / 2 // 5
let remainder = 9 % 4 // 1
These operators in Swift work the same way as in basic math.
Comparison Operators
Use them to compare values:
let isEqual = 5 == 5 // true
let isNotEqual = 3 != 4 // true
let isGreater = 7 > 5 // true
let isSmaller = 2 < 4 // true
let isGreaterOrEqual = 4 >= 4 // true
let isLessOrEqual = 3 <= 5 // true
These return a Bool
and are often used in conditions and loops.
Logical Operators
These help you write conditions using Boolean values:
let a = true
let b = false
let andResult = a && b // false
let orResult = a || b // true
let notResult = !a // false
Logical operators in Swift control the flow of decisions in your code.
Assignment Operators
These assign values and support shortcuts:
var score = 10
score += 5 // score is now 15
score -= 3 // score is now 12
Swift assignment operators make updating variables simple and quick.
When to Use Swift Operators
You’ll use a Swift operator any time you need to:
- Perform calculations (like totals, averages, percentages)
- Compare values (such as validating user input)
- Chain conditions in
if
orguard
statements - Combine strings or arrays
- Toggle Boolean states
- Write readable expressions in compact form
Operators in Swift aren’t just about math. They help you make your logic cleaner and more expressive.
Examples of Swift Operators in Practice
Using Operators in Conditions
let age = 20
if age >= 18 {
print("You can vote.")
}
The >=
operator checks if the user is eligible.
Building a Calculator
let num1 = 12.5
let num2 = 3.5
let add = num1 + num2
let divide = num1 / num2
Operators let you build arithmetic tools easily.
Boolean Toggles
var isActive = false
isActive = !isActive // true
You can flip a Boolean with the !
operator.
Combining Strings
let first = "Hello"
let last = "World"
let message = first + " " + last // "Hello World"
Use the +
operator to combine string values.
Writing Clean Loop Logic
let items = [1, 2, 3, 4, 5]
for item in items where item % 2 == 0 {
print("\(item) is even")
}
The %
operator finds even numbers by checking remainders.
Learn More About Operators in Swift
Ternary Conditional Operator
The ternary operator in Swift provides a quick way to write simple if/else
logic:
let temperature = 30
let status = temperature > 25 ? "Hot" : "Cool"
It reads like: “If temperature > 25, use 'Hot'; otherwise, use 'Cool'.”
Nil-Coalescing Operator (??
)
Swift provides ??
to supply a default value when working with optionals:
let name: String? = nil
let displayName = name ?? "Guest" // "Guest"
If the optional is nil, the value after ??
is used.
Range Operators
You can use range operators in loops, slicing, or filtering:
for i in 1...5 {
print(i) // Prints 1 to 5
}
let partial = [10, 20, 30, 40][1..<3] // [20, 30]
Use ...
for closed ranges and ..<
for half-open ranges.
Custom Operators
You can even create your own operator Swift-style if you need something specific:
infix operator **
func ** (base: Int, power: Int) -> Int {
return Int(pow(Double(base), Double(power)))
}
print(2 ** 3) // 8
Be cautious with custom operators—they can make code harder to read if misused.
Operator Overloading
You can define how existing operators behave for custom types:
struct Vector {
var x: Int
var y: Int
static func + (a: Vector, b: Vector) -> Vector {
return Vector(x: a.x + b.x, y: a.y + b.y)
}
}
let v1 = Vector(x: 1, y: 2)
let v2 = Vector(x: 3, y: 4)
let result = v1 + v2 // Vector(x: 4, y: 6)
This gives your own types Swift-operator-style functionality.
Operator Precedence and Associativity
Swift evaluates operators based on precedence rules. For example, multiplication happens before addition:
let result = 2 + 3 * 4 // 14
You can override this with parentheses:
let result = (2 + 3) * 4 // 20
Operators also have associativity. For instance, assignment (=
) is right-associative, so Swift evaluates from the right to the left.
Overflow Operators
Swift includes special operators for overflowing arithmetic:
let max = UInt8.max // 255
let wrapped = max &+ 1 // 0, wraps around
These operators (&+
, &-
, &*
) handle wraparound math intentionally.
Best Practices for Using Operators in Swift
- Don’t overuse custom operators—stick to what's readable.
- Add parentheses to make complex expressions clearer.
- Avoid chaining too many operations without clarification.
- Know your operator precedence rules.
- Use descriptive variable names to keep expressions meaningful.
- Use protocol conformance (
Equatable
,Comparable
) to unlock more operator power for custom types.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.