Menu
Coddy logo textTech

Logical Operators Part 1

Part of the Fundamentals section of Coddy's Swift journey — lesson 21 of 86.

Logical operators let you combine multiple Boolean values or conditions into a single result. The first logical operator we'll explore is the NOT operator (!), which flips a Boolean value to its opposite.

let isRaining = true
let isNotRaining = !isRaining  // false

print(!true)   // false
print(!false)  // true

The NOT operator is useful when you want to check for the opposite of a condition. If you have a variable tracking whether a user is logged in, you can easily check if they're logged out by negating it.

let isLoggedIn = false
let needsToLogin = !isLoggedIn  // true

You can also apply the NOT operator directly to comparison expressions by wrapping them in parentheses:

let age = 15
let isNotAdult = !(age >= 18)  // true

The NOT operator is simple but powerful — it gives you flexibility in how you express conditions in your code.

challenge icon

Challenge

Easy
Write a function isNotEligible that takes an age and returns whether the person is not eligible to vote.

A person is eligible to vote if they are 18 or older. Use the NOT operator to determine if they are not eligible.

Parameters:

  • age (Int): The person's age

Returns: true if the person is not eligible to vote (under 18), false if they are eligible (Bool)

Cheat sheet

The NOT operator (!) flips a Boolean value to its opposite:

let isRaining = true
let isNotRaining = !isRaining  // false

print(!true)   // false
print(!false)  // true

You can use the NOT operator to check for the opposite of a condition:

let isLoggedIn = false
let needsToLogin = !isLoggedIn  // true

The NOT operator can be applied directly to comparison expressions by wrapping them in parentheses:

let age = 15
let isNotAdult = !(age >= 18)  // true

Try it yourself

func isNotEligible(age: Int) -> Bool {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals