Chapter 22: Swift Operators

1. What are Operators?

Operators are special symbols (or sometimes words) that perform an operation on one, two, or three values.

Swift

Swift has several categories of operators. We’ll look at the most important ones in detail.

2. Arithmetic Operators (+ – * / %)

These work with numbers (Int, Double, Float, Decimal).

Swift

Compound assignment operators (very common)

Swift

Real-life example – price calculation

Swift

3. Comparison Operators (== != > < >= <=)

Return Bool (true or false)

Swift

Very common mistake beginners make:

Swift

4. Logical Operators (&& || !)

Combine or invert Bool values

Operator Name Meaning Example Result
&& AND Both must be true age >= 18 && hasLicense true only if both true
OR At least one must be true
! NOT Reverses the value !isLoggedIn true → false, false → true

Real example – form validation

Swift

Short-circuit evaluation (very important to understand)

Swift

5. Assignment Operator (=)

Swift

Compound versions (already seen):

Swift

6. Ternary Conditional Operator (?:) – very popular

Short version of if-else

Swift

More readable version with multiple conditions

Swift

7. Nil-Coalescing Operator (??)

Very common when dealing with optionals

Swift

Real usage – user profile

Swift

8. Range Operators

Very common in loops and switches

Swift

9. Identity Operators (=== !==) – only for classes

These check whether two references point to the same instance (not value equality)

Swift

10. Quick Reference Table – Most Used Operators

Category Operator(s) Example Result / Use Case
Arithmetic + – * / % price * quantity Calculations
Compound assignment += -= *= /= %= score += 100 Updating variables
Comparison == != > < >= <= age >= 18 Conditions
Logical && !
Ternary ?: isLoggedIn ? “Logout” : “Login” Short if-else
Nil-coalescing ?? name ?? “Anonymous” Safe optional unwrapping
Range … ..< 1…10, 0..<count Loops, switches, slices
Identity === !== object1 === object2 Check same instance (classes only)

11. Small Practice – Combine Operators

Try to write these using operators:

Swift

Would you like to go deeper into any specific operator group?

  • Arithmetic & compound assignment in real calculations
  • Logical operators in complex conditions
  • Ternary & nil-coalescing patterns
  • Ranges in SwiftUI / loops / switch
  • Or move to another topic (control flow, functions, optionals…)

Just tell me — we’ll continue in the same detailed, clear, teacher-like style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *