0
0
Swiftprogramming~5 mins

Logical operators in Swift

Choose your learning style9 modes available
Introduction

Logical operators help you combine or change true/false values to make decisions in your code.

Checking if two conditions are both true before running some code.
Running code if at least one of several conditions is true.
Reversing a true/false condition to do the opposite action.
Making complex decisions by combining multiple true/false checks.
Syntax
Swift
let result = condition1 && condition2  // AND operator
let result = condition1 || condition2  // OR operator
let result = !condition                 // NOT operator

AND (&&) means both conditions must be true.

OR (||) means at least one condition must be true.

NOT (!) flips true to false, and false to true.

Examples
This checks if it is both sunny and warm. Since isWarm is false, canGoOutside will be false.
Swift
let isSunny = true
let isWarm = false
let canGoOutside = isSunny && isWarm
This checks if you have a key or know the password. Since knowsPassword is true, canEnter will be true.
Swift
let hasKey = false
let knowsPassword = true
let canEnter = hasKey || knowsPassword
This flips the value of isRaining. Since it is true, stayDry will be false.
Swift
let isRaining = true
let stayDry = !isRaining
Sample Program

This program uses logical operators to decide what message to print based on whether it is the weekend and if you have homework.

Swift
import Foundation

let isWeekend = true
let haveHomework = false

if isWeekend && !haveHomework {
    print("You can relax today!")
} else if isWeekend && haveHomework {
    print("You should finish your homework.")
} else {
    print("Time to go to school.")
}
OutputSuccess
Important Notes

Use parentheses to group conditions and make your code easier to read.

Logical operators work with Boolean values: true or false.

Combining multiple logical operators can create complex conditions.

Summary

Logical operators combine true/false values to help make decisions.

AND (&&) needs both conditions true, OR (||) needs one true, NOT (!) flips true/false.

They are useful for checking multiple things at once in your code.