Menu
Coddy logo textTech

Logical Operators Part 2

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

The AND operator (&&) combines two conditions and returns true only when both conditions are true. If either condition is false, the entire expression evaluates to false.

let age = 25
let hasLicense = true

let canDrive = age >= 18 && hasLicense  // true
print(canDrive)

In this example, both conditions must be met: the person must be at least 18 years old AND have a license. Since both are true, canDrive is true. If either condition were false, the result would be false.

let temperature = 30
let isSunny = false

let perfectBeachDay = temperature > 25 && isSunny  // false

Here, even though the temperature is above 25, it's not sunny — so perfectBeachDay is false. The AND operator is essential when you need multiple requirements to be satisfied simultaneously, like checking if a user has both a valid username and password, or if a product is both in stock and within budget.

challenge icon

Challenge

Easy
Write a function canEnterClub that takes age and hasMembership and returns whether a person can enter the club.

A person can enter the club only if they are at least 21 years old AND have a membership. Both conditions must be true.

Parameters:

  • age (Int): The person's age
  • hasMembership (Bool): Whether the person has a club membership

Returns: true if the person meets both requirements, false otherwise (Bool)

Cheat sheet

The AND operator (&&) combines two conditions and returns true only when both conditions are true. If either condition is false, the entire expression evaluates to false.

let age = 25
let hasLicense = true

let canDrive = age >= 18 && hasLicense  // true

Both conditions must be met for the result to be true. If either condition is false, the entire expression is false:

let temperature = 30
let isSunny = false

let perfectBeachDay = temperature > 25 && isSunny  // false

Try it yourself

func canEnterClub(age: Int, hasMembership: Bool) -> 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