Chapter 50: Swift If (Logical Operators)
1. Why do we need logical operators inside if?
Very often, one single condition is not enough.
You want to check several things at once.
Examples of real questions we ask in code:
- “Is the user older than 18 and has a driving license?”
- “Is it weekend or is it a holiday?”
- “Is the user not a guest?”
That’s exactly what logical operators do: they let you combine or invert boolean conditions.
Swift has three logical operators:
| Operator | Name | Symbol | Meaning | Returns true when… |
|---|---|---|---|---|
| && | AND | && | Both sides must be true | Both left and right are true |
|
OR | |
||
| ! | NOT | ! | Reverse the value | The value was false (becomes true) |
2. Each operator explained with simple examples
2.1 Logical AND — && (both must be true)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let age = 20 let hasLicense = true if age >= 18 && hasLicense { print("You can drive a car 🚗") } else { print("You cannot drive yet") } |
Truth table for && (very useful to memorize):
| Left | Right | left && right |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
→ Only both true → result is true.
2.2 Logical OR — || (at least one must be true)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let isWeekend = true let isHoliday = false if isWeekend || isHoliday { print("No work today – relax! 😌") } else { print("Regular workday") } |
Truth table for ||:
| Left | Right | left || right | |--------|--------|------------------| | true | true | true | | true | false | true | | false | true | true | | false | false | false |
→ Only both false → result is false.
2.3 Logical NOT — ! (reverse)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let isGuest = true if !isGuest { print("You are a registered user – welcome!") } else { print("Please sign in") } |
Truth table for !:
| Value | !value |
|---|---|
| true | false |
| false | true |
Very common uses of !:
- !isLoading → “content is ready”
- !isError → “everything is ok”
- !hasSeenTutorial → “show tutorial”
3. Combining them — real-life examples
Example 1 – Can vote in India
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let age = 19 let isIndianCitizen = true let isDisqualified = false if age >= 18 && isIndianCitizen && !isDisqualified { print("You are eligible to vote 🗳️") } else { print("Not eligible to vote") } |
Example 2 – Show checkout button (very common in e-commerce)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let cartHasItems = true let isLoggedIn = false let hasSavedPaymentMethod = true if cartHasItems && (isLoggedIn || hasSavedPaymentMethod) { print("Show 'Proceed to Checkout' button") } else { print("Show 'Add items to cart' or 'Sign in' message") } |
Important: Parentheses (isLoggedIn || hasSavedPaymentMethod) are very helpful for clarity when mixing && and ||.
Example 3 – Password strength check
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let password = "Passw0rd!" let longEnough = password.count >= 8 let hasUppercase = password != password.lowercased() let hasDigit = password.rangeOfCharacter(from: .decimalDigits) != nil let hasSpecial = password.range(of: "[!@#$%^&*]", options: .regularExpression) != nil if longEnough && (hasUppercase || hasDigit || hasSpecial) { print("Password is strong enough 💪") } else { print("Password is too weak – please improve it") } |
4. The Most Important Behavior: Short-Circuit Evaluation
This is something that surprises many people — and understanding it prevents bugs and crashes.
Swift does NOT evaluate the right side if it doesn’t need to.
AND (&&) short-circuits
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let user: User? = nil // Safe! Right side is NOT evaluated if left is false if user != nil && user!.isPremium { print("Show premium badge") } |
If user == nil, Swift never tries to access user!.isPremium → no crash.
OR (||) short-circuits
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let hasInternet = false // Safe! Right side not called if left is true if hasInternet || fetchDataFromCache() { print("Got data") } |
If hasInternet == true, Swift skips calling fetchDataFromCache().
Very important rule to remember:
Left side is always evaluated Right side is evaluated only if necessary
This is why you should always put the cheap/safe check first:
|
0 1 2 3 4 5 6 7 8 9 10 |
// Good if user != nil && user!.hasValidToken { … } // Bad – can crash if user is nil if user!.hasValidToken && user != nil { … } |
5. Very Common Beginner Mistakes & Fixes
| Mistake | Wrong code | Correct / Better way | Why? |
|---|---|---|---|
| Writing == true everywhere | if isAdult == true { … } | if isAdult { … } | Redundant & less readable |
| Putting dangerous check first | user!.isPremium && user != nil | user != nil && user!.isPremium | Prevents crash (short-circuit safety) |
| Forgetting parentheses with mixed && / | a && b | ||
| Not using ! for negation | if isGuest == false | if !isGuest | Much more natural |
| Deep nesting instead of combining | if a { if b { if c { … } } } | if a && b && c { … } | Flatter code is easier to read |
6. Quick Reference – Logical operators inside if
| Goal | Typical code example | Notes / Tip |
|---|---|---|
| Both conditions must be true | if a && b { … } | Most common – all must pass |
| At least one condition true | `if a | |
| Invert a condition | if !isError { … } | Very frequent for “everything is ok” |
| Safe optional check | if let user, user.isPremium { … } | Modern & safe way to unwrap + check |
| Combine with range | if age >= 18 && age <= 65 { … } | Very common in eligibility checks |
7. Small Practice – Try these
- Write an if condition that checks if someone can drive a car in India:
- age ≥ 18 and has driving license and not disqualified
- Write code that shows a message if:
- user is premium or has an active trial
- Write a password check that requires:
- length ≥ 8 and (has uppercase or has number or has special character)
Paste your conditions here if you want feedback or want to see cleaner versions!
What would you like to explore next?
- guard statement (very important companion to if)
- switch statement (often cleaner than long if…else if)
- if let / optional binding in depth
- Combining logical operators with ranges and comparisons
- Or move to another topic (loops, functions, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
