Chapter 23: Operators

1. What is an Operator?

An operator is a special symbol (or sometimes a word) that tells Swift to perform an action on one or more values.

Examples you already know:

Swift

Swift has many categories of operators. We will look at the most important ones in detail — the ones you will use almost every day.

2. Arithmetic Operators — + – * / %

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

Swift

Important behavior with floating-point numbers:

Swift

Compound assignment — very common shorthand

Swift

Realistic example – shopping cart

Swift

3. Comparison Operators — == != > < >= <=

These always return a Bool (true or false).

Swift

Very frequent beginner mistake:

Swift

Another common pattern:

Swift

4. Logical Operators — && || !

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

Real example – access control

Swift

Short-circuit evaluation (very important concept)

Swift

5. Nil-Coalescing Operator — ??

Very common when dealing with optionals.

Swift

Real-life usage – profile screen

Swift

6. Ternary Conditional Operator — ? :

Short version of if-else.

Swift

More readable with multiple conditions

Swift

7. Range Operators — … ..<

Very common in loops, switches, array slices.

Swift

Very common in switch statements

Swift

8. Quick Summary Table – Most Used Operators

Category Operators Example Typical Use Case
Arithmetic + – * / % price * quantity Calculations
Compound assignment += -= *= /= %= total += tax Updating variables
Comparison == != > < >= <= age >= 18 Conditions
Logical && !
Nil-coalescing ?? name ?? “Guest” Safe optional defaults
Ternary ?: isDarkMode ? “Dark” : “Light” Short if-else
Range … ..< 1…10, 0..<array.count Loops, switches, array slices
Identity (classes) === !== objectA === objectB Check same instance

9. Small Practice – Combine Operators

Try writing these:

  1. Calculate final price: base = 999.99 + 18% tax
  2. Check if user can enter: age ≥ 18 AND has ticket AND NOT banned
  3. Set greeting: “Welcome back” if logged in, else “Hello guest”

Would you like to go deeper into any group?

  • Arithmetic & money calculations in detail
  • Logical operators in complex real conditions
  • Ranges + switch + array slicing
  • Ternary vs if-else – when to choose which
  • Or move to next topic (control flow, functions, optionals…)

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

You may also like...

Leave a Reply

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