Chapter 19: Swift Booleans
1. What is a Boolean?
A Boolean (or Bool in Swift) is the simplest data type: It can only have two possible values:
- true
- false
Think of it as a light switch:
- true = light is ON
- false = light is OFF
Booleans are used everywhere to answer yes/no questions:
- Is the user logged in?
- Is it raining?
- Does the password meet the requirements?
- Is the form valid?
- Should we show the premium banner?
2. How to write Booleans – basic syntax
|
0 1 2 3 4 5 6 7 8 9 |
let isLoggedIn = true let hasPremium = false let isRaining = false let buttonIsEnabled = true |
Important facts right away:
- The values are exactlytrue and false (lowercase, no quotes)
- You cannot write True, TRUE, yes, 1, 0, etc.
- Swift is very strict about this
|
0 1 2 3 4 5 6 7 8 9 |
// These are WRONG and will NOT compile let a = True // ❌ let b = "true" // ❌ (this is String, not Bool) let c = 1 // ❌ (this is Int) |
3. Where Booleans come from in real code
From comparisons
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let age = 19 let canVote = age >= 18 // true let temperature = 36.6 let hasFever = temperature > 37.5 // false let password = "secret123" let isStrongEnough = password.count >= 8 // true |
From functions & methods
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let text = "Swift is fun" let containsSwift = text.contains("Swift") // true let isEmpty = text.isEmpty // false let numbers = [1, 3, 5, 7] let hasEven = numbers.contains { $0 % 2 == 0 } // false |
From user interface state
|
0 1 2 3 4 5 6 7 |
let isDarkModeEnabled = traitCollection.userInterfaceStyle == .dark // true or false let isNetworkAvailable = reachability.connection != .none // true or false |
4. Combining Booleans – logical operators (very important!)
Swift has three main operators for working with multiple booleans:
| Operator | Meaning | Symbol | Example | Result |
|---|---|---|---|---|
| AND | Both true | && | isAdult && hasLicense | true only if both are true |
| OR | At least one true | |
||
| NOT | Reverse | ! | !isLoggedIn | true becomes false, false becomes true |
Real examples:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let age = 20 let hasLicense = true let canDrive = age >= 18 && hasLicense // true let isWeekend = true let isHoliday = false let canSleepLate = isWeekend || isHoliday // true let isGuest = false let showLoginButton = !isGuest // true |
5. Real-life examples – very common patterns
Example 1 – Login / access control
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let emailIsValid = email.contains("@") && email.contains(".") let passwordIsLongEnough = password.count >= 8 let passwordsMatch = password == confirmPassword let canRegister = emailIsValid && passwordIsLongEnough && passwordsMatch if canRegister { print("Ready to create account") } else { print("Please fix the errors") } |
Example 2 – Showing / hiding UI elements
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let userIsPremium = subscriptionStatus == .active let hasNewMessages = unreadCount > 0 let shouldShowBanner = userIsPremium && hasNewMessages if shouldShowBanner { bannerView.isHidden = false } else { bannerView.isHidden = true } |
Example 3 – Form validation (very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func isRegistrationFormValid( name: String, email: String, password: String, termsAccepted: Bool ) -> Bool { let nameIsNotEmpty = !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty let emailLooksGood = email.contains("@") && email.contains(".") let passwordIsStrong = password.count >= 8 let agreedToTerms = termsAccepted return nameIsNotEmpty && emailLooksGood && passwordIsStrong && agreedToTerms } |
Example 4 – Game logic
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let playerHasKey = true let doorIsLocked = true let bossIsDefeated = false let canEnterSecretRoom = playerHasKey && !doorIsLocked || bossIsDefeated // true if (has key AND door unlocked) OR boss is defeated |
6. Common Beginner Mistakes & How to Avoid Them
| Mistake | Wrong / Dangerous code | Correct way | Why? |
|---|---|---|---|
| Using 1 / 0 instead of true/false | let active = 1 | let active = true | Swift is strict — 1 is Int, not Bool |
| Writing True / TRUE | let isOK = True | let isOK = true | Case-sensitive — only lowercase true |
| Using == true everywhere | if isLoggedIn == true { … } | if isLoggedIn { … } | Cleaner & idiomatic |
| Forgetting to use ! for negation | if isGuest == false | if !isGuest or if !isGuest { … } | Much more readable |
| Overcomplicating conditions | if (age >= 18 && hasID == true) |
… |
7. Nice-to-know shortcuts & patterns
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Instead of this: if isEnabled == true { … } // Write simply: if isEnabled { … } // Instead of this: if isError == false { … } // Write: if !isError { … } // Toggle a boolean (very common) isDarkMode.toggle() // true → false, false → true // Default value when optional Bool let isPremium = user.isPremium ?? false |
8. Quick summary – when & where you use Bool
| Situation | Typical variable name | Typical value source |
|---|---|---|
| User state | isLoggedIn, isPremium, isVerified | From auth / subscription |
| UI visibility | shouldShowBanner, isLoading, hasError | From view model / network state |
| Form validation | isValid, canSubmit, termsAccepted | From text fields + checkboxes |
| Permissions / capabilities | hasCameraAccess, canDrive, isAdult | From age check, permissions |
| Game / app logic | isGameOver, levelCompleted, hasKey | From game state |
Which part of Booleans would you like to explore more deeply next?
- More complex logical conditions (&&, ||, combining many conditions)
- Booleans in SwiftUI (how they drive the UI)
- Optional Booleans (Bool?) – when and why they appear
- Using booleans with enums (very powerful pattern)
- Or move to another topic (strings, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, teacher-like style 😊
