Swift Operators

Swift Introduction

➕➖ Swift Operators (Complete & Easy Guide)

In Swift Operators are special symbols used to perform operations on values and variables—like calculation, comparison, or logic.

 Types of Swift Operators

Swift operators are divided into these main categories:

  1. Arithmetic Operators

  2. Assignment Operators

  3. Comparison Operators

  4. Logical Operators

  5. Range Operators

  6. Ternary Conditional Operator

  7. Nil-Coalescing Operator

Let’s understand each one clearly 👇


1️⃣ Arithmetic Operators

Used for mathematical calculations.

let a = 10
let b = 3
print(a + b) // Addition → 13
print(a b) // Subtraction → 7
print(a * b) // Multiplication → 30
print(a / b) // Division → 3
print(a % b) // Modulus → 1

2️⃣ Assignment Operators

Used to assign values.

var x = 5
x += 3 // x = x + 3 → 8
x -= 2 // 6
x *= 2 // 12
x /= 3 // 4

3️⃣ Comparison Operators

Used to compare two values. Result is Bool (true / false).

let p = 10
let q = 20
print(p == q) // false
print(p != q) // true
print(p > q) // false
print(p < q) // true
print(p >= q) // false
print(p <= q) // true

4️⃣ Logical Operators

Used with Boolean values.

 AND (&&)

true && false // false

 OR (||)

true || false // true

 NOT (!)

!true // false

5️⃣ Range Operators (Very Important 🔥)

 Closed Range (...)

Includes both start and end.

for i in 1...5 {
print(i)
}

Output: 1 2 3 4 5


 Half-Open Range (..<)

Excludes the last value.

for i in 1..<5 {
print(i)
}

Output: 1 2 3 4


 One-Sided Range

let numbers = [10, 20, 30, 40, 50]
print(numbers[2...]) // 30, 40, 50

6️⃣ Ternary Conditional Operator

Shortcut for if–else.

let age = 20
let result = age >= 18 ? "Adult" : "Minor"
print(result)

7️⃣ Nil-Coalescing Operator (??)

Used with Optionals.

let name: String? = nil
print(name ?? "Guest")

✔ Prevents crashes
✔ Very common in Swift


8️⃣ Identity Operators (Class Types)

Used to check reference equality.

class Person { }

let p1 = Person()
let p2 = p1

print(p1 === p2) // true
print(p1 !== p2) // false


❌ Common Mistakes

❌ Mixing different types:

let a = 10
let b = 2.5
// print(a + b) ❌

✅ Correct:

print(Double(a) + b)

🧠 Summary Table

Operator TypeExample
Arithmetic+ - * / %
Assignment= += -=
Comparison== != > <
Logical`&&
Range... ..<
Ternary? :
Nil-Coalescing??

You may also like...