0
0
Swiftprogramming~5 mins

Bool type and logical operators in Swift

Choose your learning style9 modes available
Introduction

The Bool type helps us represent true or false values. Logical operators let us combine or change these true/false values to make decisions in code.

Checking if a light is on or off in a smart home app.
Deciding if a user is logged in before showing their profile.
Determining if a number is positive and even before processing it.
Checking multiple conditions like if a door is locked and the alarm is set.
Syntax
Swift
let isTrue: Bool = true
let isFalse: Bool = false

// Logical operators
let andResult = true && false  // AND
let orResult = true || false   // OR
let notResult = !true          // NOT

Bool values are either true or false.

Logical operators combine Bool values to make new Bool values.

Examples
AND (&&) returns true only if both a and b are true.
Swift
let a = true
let b = false
let result = a && b
OR (||) returns true if either a or b is true.
Swift
let a = true
let b = false
let result = a || b
NOT (!) flips the value: true becomes false, false becomes true.
Swift
let a = true
let result = !a
Sample Program

This program checks if it is raining and if you have an umbrella. It uses AND (&&) and NOT (!) to decide what message to print.

Swift
import Foundation

let isRaining = true
let haveUmbrella = false

if isRaining && haveUmbrella {
    print("You can go outside safely.")
} else if isRaining && !haveUmbrella {
    print("Better stay inside or get wet.")
} else {
    print("Enjoy your day outside!")
}
OutputSuccess
Important Notes

Use parentheses to group conditions for clarity, like (a && b) || c.

Logical operators only work with Bool values, not numbers or strings.

Summary

Bool type stores true or false values.

Use && for AND, || for OR, and ! for NOT operations.

Logical operators help make decisions by combining true/false values.