Booleans
In this page:
let name: Bool = true
let result = a >= b // == != < > <= >=
let combined = x && y || !z
Declaring Booleans
A Bool variable holds either true or false, often as the result of a comparison.
Example: Declaring Booleans
// Declare a constant `isSwiftFun`, set to `true`
let isSwiftFun = true
// Declare a constant `isDifficult`, set to `false`
let isDifficult = false
// Print "Is Swift fun? \(isSwiftFun)" to the console
print("Is Swift fun? \(isSwiftFun)")
// Print "Is it too difficult? \(isDifficult)" to the console
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
// Declare a constant `age`, set to `20`
let age = 20
// Declare a constant `isAdult`, set to `age >= 18`
let isAdult = age >= 18
// Print "Is an adult: \(isAdult)" to the console
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
// Declare a constant `hasTicket`, set to `true`
let hasTicket = true
// Declare a constant `hasID`, set to `false`
let hasID = false
// Declare a constant `canEnter`, set to `hasTicket && hasID`
let canEnter = hasTicket && hasID
// Print "Can enter: \(canEnter)" to the console
print("Can enter: \(canEnter)")
// Print "Missing ID: \(!hasID)" to the console
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: