Swift Operators

Symbols that perform operations on values and variables

⚡ What are Swift Operators?

Operators are special symbols that perform operations on values and variables. Swift provides arithmetic operators for math, comparison operators for testing, and logical operators for combining conditions in your code.


let sum = 5 + 3        // Arithmetic operator
let isEqual = sum == 8  // Comparison operator
let result = true && false // Logical operator
                                    

Types of Swift Operators

Arithmetic

Math operations like +, -, *, /

let sum = 10 + 5    // 15
let product = 4 * 3  // 12
⚖️

Comparison

Compare values with ==, !=, <, >

let isEqual = 5 == 5  // true
let isGreater = 10 > 3 // true
🔗

Logical

Combine conditions with &&, ||, !

let both = true && false // false
let either = true || false // true
📝

Assignment

Assign values with =, +=, -=

var count = 5
count += 3  // count is now 8

🔹 Assignment Operators

The assignment operator (=) assigns a value to a variable:

// Basic assignment
var name = "Swift"
var age = 25

// Compound assignment operators
var score = 100
score += 10    // score = score + 10 (now 110)
score -= 5     // score = score - 5 (now 105)
score *= 2     // score = score * 2 (now 210)
score /= 3     // score = score / 3 (now 70)

// String assignment
var message = "Hello"
message += " World"  // message is now "Hello World"

print("Final score: \(score)")
print("Message: \(message)")

Output:

Final score: 70

Message: Hello World

🔹 Unary Operators

Unary operators work on a single value:

// Unary minus (negation)
let positiveNumber = 42
let negativeNumber = -positiveNumber  // -42

// Unary plus (rarely used)
let explicitPositive = +42

// Logical NOT operator
let isTrue = true
let isFalse = !isTrue  // false

// Increment and decrement (not available in Swift)
// Use += 1 and -= 1 instead
var counter = 5
counter += 1  // counter is now 6
counter -= 1  // counter is now 5

print("Negative: \(negativeNumber)")
print("Is false: \(isFalse)")
print("Counter: \(counter)")

Output:

Negative: -42

Is false: false

Counter: 5

🔹 Ternary Conditional Operator

The ternary operator is a shortcut for simple if-else statements:

// Ternary operator: condition ? valueIfTrue : valueIfFalse
let age = 18
let status = age >= 18 ? "Adult" : "Minor"

let score = 85
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"

// Equivalent if-else statement
let temperature = 75
var weather: String
if temperature > 80 {
    weather = "Hot"
} else {
    weather = "Cool"
}

// Same result with ternary operator
let weatherTernary = temperature > 80 ? "Hot" : "Cool"

print("Status: \(status)")
print("Grade: \(grade)")
print("Weather: \(weatherTernary)")

Output:

Status: Adult

Grade: B

Weather: Cool

🔹 Nil-Coalescing Operator

The nil-coalescing operator (??) provides a default value for optionals:

// Nil-coalescing operator: optional ?? defaultValue
let optionalName: String? = nil
let userName = optionalName ?? "Guest"

let optionalAge: Int? = 25
let userAge = optionalAge ?? 0

// Chaining nil-coalescing operators
let firstName: String? = nil
let lastName: String? = nil
let displayName = firstName ?? lastName ?? "Unknown User"

// Using with dictionary values
let userInfo = ["email": "[email protected]"]
let email = userInfo["email"] ?? "No email provided"
let phone = userInfo["phone"] ?? "No phone provided"

print("User: \(userName)")
print("Age: \(userAge)")
print("Display name: \(displayName)")
print("Email: \(email)")

Output:

User: Guest

Age: 25

Display name: Unknown User

Email: [email protected]

🔹 Range Operators

Swift provides operators to create ranges of values:

// Closed range operator (includes both ends)
let closedRange = 1...5  // 1, 2, 3, 4, 5

// Half-open range operator (excludes upper bound)
let halfOpenRange = 1..<5  // 1, 2, 3, 4

// One-sided ranges
let fromStart = ...3     // up to and including 3
let toEnd = 2...         // from 2 to the end

// Using ranges in loops
print("Closed range:")
for number in 1...3 {
    print("Number: \(number)")
}

print("\nHalf-open range:")
for index in 0..<3 {
    print("Index: \(index)")
}

// Using ranges with arrays
let fruits = ["Apple", "Banana", "Cherry", "Date"]
let firstTwo = fruits[0..<2]  // ["Apple", "Banana"]
print("\nFirst two fruits: \(Array(firstTwo))")

Output:

Closed range:

Number: 1

Number: 2

Number: 3

Half-open range:

Index: 0

Index: 1

Index: 2

First two fruits: ["Apple", "Banana"]

🧠 Test Your Knowledge

What does the nil-coalescing operator (??) do?