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) // trueThe 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 // trueYou can also apply the NOT operator directly to comparison expressions by wrapping them in parentheses:
let age = 15
let isNotAdult = !(age >= 18) // trueThe NOT operator is simple but powerful — it gives you flexibility in how you express conditions in your code.
Challenge
EasyWrite 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) // trueYou can use the NOT operator to check for the opposite of a condition:
let isLoggedIn = false
let needsToLogin = !isLoggedIn // trueThe NOT operator can be applied directly to comparison expressions by wrapping them in parentheses:
let age = 15
let isNotAdult = !(age >= 18) // trueTry it yourself
func isNotEligible(age: Int) -> Bool {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input