Skip to content
AgileLogics
4 min read

Booleans and Comparisons

Prerequisites: Data types and type inference

A Boolean (Bool) is a yes/no value: true or false. Comparisons produce Booleans:

let age = 20

print(age > 18)
print(age == 21)
print(age != 21)
print("swift" == "swift")
print("apple" < "banana")
true
false
true
true
true
Operator Meaning
== equal to
!= not equal to
> < greater / less than
>= <= greater / less or equal

Strings compare alphabetically (by Unicode order), so "apple" < "banana" is true.

Only Bool is a condition

Swift is strict: a condition must be an actual Bool. Numbers and strings are never treated as true or false:

let count = 3
if count {
    print("has items")
}
error: type 'Int' cannot be used as a boolean; test for '!= 0' instead

Write what you mean: if count > 0, if !name.isEmpty.

Toggling

toggle() flips a Bool variable:

var isDarkMode = false
isDarkMode.toggle()
print(isDarkMode)
true

Name Boolean values so they read as yes/no questions: isEnabled, hasAccount, canEdit.