Swift Booleans
A Boolean can only be one of two values: true or false. Swift's Boolean type is called Bool. Booleans are the result of every comparison and they drive every decision your program makes.
Bool values
let isLoggedIn = true
var hasUnreadMessages: Bool = false
print(isLoggedIn)
print(hasUnreadMessages)
hasUnreadMessages = true
print(hasUnreadMessages)
print(type(of: isLoggedIn))true
false
true
Bool
Tip: Name Booleans so they read like a yes/no question:
isVisible,hasPremium,canEdit,shouldRetry.
Booleans from comparisons
Comparison operators return a Bool, which you can store in a constant:
let battery = 18
let isLow = battery < 20
let isFull = battery == 100
print("Low battery: \(isLow)")
print("Fully charged: \(isFull)")
print(10 > 9, "a" == "A", 3 != 4)Low battery: true
Fully charged: false
true false true
No "truthy" values
In many languages 0, "" or nil act like false. Swift has no such rule: a condition must be a real Bool. This prevents a whole class of subtle bugs.
let unread = 3
if unread {
print("You have mail")
}error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:2:4: error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
1 | let unread = 3
2 | if unread {
| `- error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
3 | print("You have mail")
4 | }
The fix is to say what you mean: if unread > 0 { … }.
Combining Booleans
| Expression | Result |
|---|---|
true && false |
false |
true || false |
true |
!true |
false |
let isWeekend = true
let isHoliday = false
let isRaining = true
let canSleepIn = isWeekend || isHoliday
let goToBeach = canSleepIn && !isRaining
print("Sleep in: \(canSleepIn)")
print("Beach day: \(goToBeach)")Sleep in: true
Beach day: false
toggle()
toggle() flips a var Bool in place — very common for on/off switches in apps:
var darkMode = false
darkMode.toggle()
print(darkMode)
darkMode.toggle()
print(darkMode)true
false
Booleans and collections
Many collection methods return a Bool, which makes for very readable conditions:
let scores = [72, 95, 64, 88]
print(scores.isEmpty)
print(scores.contains(95))
print(scores.allSatisfy { $0 >= 60 })
print(scores.contains { $0 > 90 })false
true
true
true
The { $0 >= 60 } part is a closure — a small inline function that you will meet in the Closures chapter.
Test yourself
What is the value of !(5 > 3) || 2 == 2?
- true
- false
- nil
- It does not compile
Why does if count { … } fail when count is an Int?
- Int needs to be unwrapped first
- Swift conditions must be of type Bool — there are no truthy numbers
ifneeds parenthesescountis a reserved word
What does flag.toggle() do?
- Returns the opposite value without changing
flag - Flips the value stored in
flag - Sets
flagto true - Prints the value