Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Boolean Values in Swift
Written by Team Kodeco

A Boolean value, also known as a logical value, is a data type that can only have two values: true or false. Boolean values are commonly used in control flow statements, such as if-else statements, to make decisions in your code.

Here is an example of how to use a Boolean value in an if-else statement:

let isRainy: Bool = true

if isRainy {
  print("Bring an umbrella.")
} else {
  print("Enjoy the sunny weather.")
}
// Output: Bring an umbrella.

In this example, the variable isRainy is assigned the value true, so the code inside the if block is executed and the output is “Bring an umbrella.

The above example uses type annotation to manually specify the type of isRainy as bool. Alternatively, it could have used type inference as follows:

let isRainy = true
print(type(of: isRainy)) // Prints Bool

You can also use comparison operators to assign a Boolean value to a variable:

let temperature = 72
let isWarm = temperature > 70
print(isWarm) // Prints true

In this example, the variable isWarm is assigned the value true, because the temperature is greater than 70.

You can think of a Boolean value like a light switch. It can only be in one of two states, on or off. In the same way, a Boolean value can only be true or false.

© 2024 Kodeco Inc.