Start with Swift

Booleans in Swift

Learn booleans in Swift: the Bool type, comparison operators, combining conditions with logical operators, toggle, and why Swift has no truthiness.

8 minute lesson

~~~

This tutorial belongs to the Swift series

Swift provides the Bool type to represent truth values. A Bool can only hold two values: true or false.

You declare a boolean like any other variable:

var done = false

Since we declared it with var, we can reassign it later:

var done = false
done = true

You can also write the type explicitly:

var done: Bool = false

Where do booleans come from?

Most of the time you don’t type true or false by hand. You get booleans as the result of comparison operators:

let age = 18

age == 18 // true
age != 21 // true
age > 16  // true
age < 10  // false

Each of those expressions produces a Bool, and you can store it in a constant with a meaningful name:

let canVote = age >= 18 // true

My advice is to name booleans like a question with a yes/no answer: canVote, isLoggedIn, hasTicket. The code that uses them reads much better.

Combining booleans

Swift gives you three logical operators: && (and), || (or), and ! (not).

let isWeekend = true
let isSunny = false

isWeekend && isSunny // false
isWeekend || isSunny // true
!isSunny             // true

&& is true only when both sides are true. || is true when at least one side is. ! flips the value.

You’ll use them all the time in conditionals:

let age = 25
let hasTicket = true

if age >= 18 && hasTicket {
    print("Welcome in!")
}

Flipping a boolean with toggle()

When you want to invert a boolean, you could write done = !done. Swift has a nicer way, the toggle() method:

var done = false
done.toggle() // done is now true
done.toggle() // done is now false

It only works on variables declared with var, because it changes the value in place.

Swift has no truthiness

In JavaScript you can write if (count) and any non-zero number counts as true. Swift does not allow that. A condition must be a real Bool:

let count = 3

if count {
    // does not compile
}

You have to write the comparison explicitly:

let count = 3

if count > 0 {
    print("We have items")
}

This feels more verbose at first, but it removes an entire category of bugs. You always say exactly what you’re checking.

The = vs == mistake

A classic bug in C-family languages is typing = (assignment) when you meant == (comparison). The condition assigns a value and the code runs when you didn’t expect it to.

Swift catches this at compile time:

var logged = false

if logged = true {
    // does not compile
}

An assignment does not return a value in Swift, and an if condition must be a boolean expression. So the compiler stops you before this mistake ever reaches your users.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →