Swift — Operators
Arithmetic operators
let a = 10, b = 3
print("Add: \(a + b)") // 13
print("Sub: \(a - b)") // 7
print("Mul: \(a * b)") // 30
print("Div: \(a / b)") // 3
print("Mod: \(a % b)") // 1
Comparison operators
print(5 == 5) // true
print(5 != 3) // true
print(5 > 3) // true
print(5 < 3) // false
print(5 >= 5) // true
print(5 <= 3) // false
Logical operators
let a = true, b = false
print(a && b) // false (AND)
print(a || b) // true (OR)
print(!a) // false (NOT)
Range operators
// Closed range
for i in 1...5 {
print(i, terminator: " ")
}
print() // 1 2 3 4 5
// Half-open range
for i in 0..<5 {
print(i, terminator: " ")
}
print() // 0 1 2 3 4
// One-sided range
let arr = [10, 20, 30, 40, 50]
print(arr[2...]) // [30, 40, 50]
Nil coalescing
let name: String? = nil
let display = name ?? "Unknown"
print(display) // Unknown
Ternary operator
let x = 10
let label = x > 5 ? "big" : "small"
print(label) // big
Mini Practice
Write Swift code that:
- Demonstrates all arithmetic operators
- Uses range operators in a for loop
- Uses nil coalescing for defaults
- Shows the ternary operator
Up Next
In the next lesson, you'll learn about Booleans — logical values in Swift.
Related Topics
Frequently Asked Questions about Operators
What is Operators in Swift?
Operators is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Operators?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Operators.
Why is Operators important in Swift?
Operators is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.