If you’ve been working with Swift for a while, you’ve probably been using operators without giving them much thought. They’re the symbols that let you perform calculations, compare values, and combine logic. Some examples include +
, -
, ==
, and &&
. Understanding operators properly will help you write cleaner, more expressive Swift code.
What Are Operators?
An operator is a symbol that tells Swift to perform a specific operation on one, two, or three values. They are like the verbs of programming, that perform action on data types
Swift groups operators by how many values they work with:
- Unary operators work on a single value (
-5
,!true
) - Binary operators work on two values (
2 + 3
,name == "Alice"
) - Ternary operators work on three values (Swift has one:
condition ? valueIfTrue : valueIfFalse
)
Let’s explore the most important ones you’ll use daily.
Arithmetic Operators
Probably, the most recognisable operators are arithmetic operators. They do maths.
Basic Arithmetic:
let sum = 10 + 5 // 15
let difference = 10 - 5 // 5
let product = 10 * 5 // 50
let quotient = 10 / 5 // 2
let remainder = 10 % 3 // 1 (modulo operator)
The modulo operator (%
) gives you the remainder after division. It’s useful for things like checking if a number is even (number % 2 == 0
).
String Concatenation:
The +
operator also works with strings:
let greeting = "Hello, " + "world!" // "Hello, world!"
let fullName = firstName + " " + lastName
Typical Use Cases:
- Calculating totals, averages, and percentages
- Building dynamic strings and messages
- Creating animations with time-based calculations
Assignment Operators
Assignment operators let you store values in constants or variables. They also let you update variables.
Basic Assignment:
var score = 100 // Assigns 100 to score
var playerName = "Alex" // Assigns "Alex" to playerName
Compound Assignment:
These operators perform an operation and assign the result back to the variable:
var points = 10
points += 5 // points is now 15 (same as points = points + 5)
points -= 3 // points is now 12
points *= 2 // points is now 24
points /= 4 // points is now 6
points %= 4 // points is now 2
Compound assignment operators make your code more concise and show your intent clearly.
Typical Use Cases:
- Updating counters and scores in games
- Accumulating values in loops
- Modifying properties based on user input
Comparison Operators
Comparison operators let you compare values. They return with a true
or false
.
Examples:
let age = 25
age == 25 // true (equal to)
age != 30 // true (not equal to)
age > 18 // true (greater than)
age >= 25 // true (greater than or equal to)
age < 30 // true (less than)
age <= 25 // true (less than or equal to)
String Comparison:
let name = "Alice"
name == "Alice" // true
name != "Bob" // true
name < "Bob" // true (alphabetical order)
Typical Use Cases:
- Validating user input (checking ages, passwords)
- Controlling flow with
if
statements - Sorting and filtering collections
- Setting up conditional logic in your apps
Logical Operators
Logical operators let you combine or invert boolean values. They can be combined to create complex conditiona logic.
The Three Logical Operators:
let isGryffindor = false
let hasInvisibilityCloak = true
// Logical NOT (!)
!isGryffindor // true (not brave, maybe clever)
!hasInvisibilityCloak // false (no sneaking around tonight)
// Logical AND (&&)
isGryffindor && hasInvisibilityCloak // false (Harry would be proud)
isGryffindor && !hasInvisibilityCloak // false (just a regular Gryffindor)
// Logical OR (||)
isGryffindor || hasInvisibilityCloak // true (either brave or sneaky)
!isGryffindor || hasInvisibilityCloak // true (Ravenclaw with a cloak? Genius!)
Practical Example:
let age = 14
let hasPermissionFromProfessorMcGonagall = true
if age >= 17 || (age >= 14 && hasPermissionFromProfessorMcGonagall) {
print("Welcome to the Yule Ball!")
} else {
print("Sorry, back to the common room!")
}
Typical Use Cases:
- Form validation (checking multiple conditions)
- User authentication and authorisation
- Feature flags and conditional functionality
- Game logic and state management
Range Operators
Swift’s range operators are incredibly handy for working with sequences of values.
Closed Range (...
):
let range = 1...5 // Includes 1, 2, 3, 4, 5
for number in 1...5 {
print(number) // Prints 1 through 5
}
Half-Open Range (..<
):
let array = ["a", "b", "c", "d"]
for index in 0..<array.count { // 0, 1, 2, 3 (excludes 4)
print(array[index])
}
One-Sided Ranges:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let firstThree = numbers[...2] // [1, 2, 3]
let lastThree = numbers[7...] // [8, 9, 10]
let middleSection = numbers[2..<8] // [3, 4, 5, 6, 7, 8]
Typical Use Cases:
- Iterating through collections with
for
loops - Slicing arrays and strings
- Creating numerical sequences
- Validating ranges of input values
Nil-Coalescing Operator
The nil-coalescing operator (??
) works with optionals. It provides a default value when an optional is nil
.
Example:
let favouritePokemon: String? = nil
let starter = favouritePokemon ?? "Pikachu" // "Pikachu"
let pokedexNumber: Int? = nil
let number = pokedexNumber ?? 25 // 25
Chaining Multiple Values:
You can chain multiple optional values using the nil-coalescing operator until you get to a default value.
let preferredName = user.nickname ?? user.firstName ?? user.email ?? "Ash"
Typical Use Cases:
- Providing fallback values for user data
- Setting default configuration values
- Handling API responses that might be missing data
- Creating user-friendly displays when data is unavailable
Ternary Conditional Operator
Swift’s only ternary operator is a compact way to choose between two values based on a condition. It is essentially an inline if statement.
Syntax:
let result = condition ? valueIfTrue : valueIfFalse
Examples:
let playerAge = 17
let lobbyStatus = playerAge >= 18 ? "Verdansk Veteran" : "Rookie Recruit" // "Rookie Recruit"
let killstreak = 85
let rank = killstreak >= 90 ? "Nuke Incoming" : killstreak >= 80 ? "Chopper Gunner" : "UAV" // "Chopper Gunner"
// Setting button text based on state
let deployButtonTitle = isLoading ? "Deploying..." : "Drop In"
When to Use It:
The ternary operator is great for simple, short conditions. But think about clarity vs brevity when using it. An if statement is more verbose but more clear.
Typical Use Cases:
- Setting UI labels and button text
- Choosing between two simple values
- Conditional styling and formatting
- Quick validation messages
Operator Precedence
When you combine multiple operators, Swift follows specific rules about which operations happen first.
Example:
let result = 2 + 3 * 4 // 14, not 20 (multiplication happens first)
let clarified = 2 + (3 * 4) // Same as above, but clearer
let different = (2 + 3) * 4 // 20 (addition happens first)
Best Practice:
When in doubt, use parentheses to make your intentions clear. Your future self will thank you.
Overloading and Custom Operators
Swift lets you define how operators work with your own types, but this is an advanced topic. For now, it’s enough to know that operators like +
and ==
can work differently depending on what types you’re using them with.
Example:
// + works with numbers
let sum = 5 + 3 // 8
// + also works with strings
let greeting = "Hello" + " world" // "Hello world"
// + even works with arrays
let combined = [1, 2] + [3, 4] // [1, 2, 3, 4]
Summary
Operators are the building blocks that make your Swift code come alive. Here’s what we’ve covered:
- Arithmetic operators for calculations and string building
- Assignment operators for storing and updating values
- Comparison operators for checking relationships
- Logical operators for combining conditions
- Range operators for working with sequences
- Nil-coalescing for handling optional values safely
- Ternary conditional for quick value selection
The more comfortable you become with operators, the more expressive and concise your Swift code will be.
Happy coding!