Booleans
In this page:
Declaring Booleans
A Bool variable holds either true or false, often as the result of a comparison.
Example: Declaring Booleans
let isSwiftFun = true
let isDifficult = false
print("Is Swift fun? \(isSwiftFun)")
print("Is it too difficult? \(isDifficult)")
Login to try C/C++/Java/PHP code in the editor
Comparison Operators Produce Booleans
Comparing two values with ==, !=, <, >, <=, or >= always produces a Bool result.
Example: Comparison Operators Produce Booleans
let age = 20
let isAdult = age >= 18
print("Is an adult: \(isAdult)")
Login to try C/C++/Java/PHP code in the editor
Combining Booleans with Logical Operators
The && (logical AND), || (logical OR), and ! (logical NOT) operators combine or invert boolean values to build more complex conditions.
Example: Combining Booleans with Logical Operators
let hasTicket = true
let hasID = false
let canEnter = hasTicket && hasID
print("Can enter: \(canEnter)")
print("Missing ID: \(!hasID)")
Login to try C/C++/Java/PHP code in the editor
- Comparing a boolean to
trueexplicitly, e.g.if isReady == true, instead of the cleanerif isReady. - Assuming any non-zero number counts as true like in C; Swift's
Boolis a distinct type and numbers are never implicitly converted to booleans. - Forgetting that
&&and||short-circuit, so a later expression might not even be evaluated.
Boolhas exactly two values:trueandfalse.- Comparison operators (
==,<,>, etc.) produceBoolresults. - Logical operators
&&(and),||(or), and!(not) combine boolean values. - Unlike C, Swift never treats numbers as implicitly true or false.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: