Understanding Logical Operators
Introduction to logical Operators
Logical operators are essential in Swift programming, enabling developers to perform boolean logic operations on multiple expressions. These operators return true or false based on the evaluation of conditions and are widely used in loops and conditional statements to control program flow effectively.
List of Swift Logical Operators
Operator | Name | Example | Output |
---|---|---|---|
&& | AND | true && false | false |
|| | OR | true || false | true |
! | NOT | !true | false |
Using the AND (&&) Operator
The && operator returns true only if both expressions evaluate to true. If any one of them is false, the result will be false.
Syntax
Expression1 && Expression2
Example: Checking Eligibility for an Exam
import
Foundation
let age
= 22
let height
= 185
if (age
> 18)
&& (height
> 182) {
print("You are eligible for the Police exam")
} else {
print("You are not eligible")
}
Output
Using the OR (||) Operator
The || operator returns true if at least one of the expressions evaluates to true. If both are false, the result will be false.
Syntax:
Expression1 || Expression2
Example: Checking Job Eligibility
import
Foundation
let marks
= 640
let experience
= 3
if (marks
> 500)
|| (experience
> 4) {
print("You are eligible for the PO Post")
} else {
print("You are not eligible")
}
Output
Using the NOT (!) Operator
The ! operator inverts a boolean value. If the condition is true, it turns false, and vice versa.
!Expression
Example: Inverting a Boolean Expression
import
Foundation
let x
= 20
let y
= 40
if !(x
> 0
&& y
> 0) {
print("Given values are greater than 0")
} else {
print("Given values are less than 0")
}