Swift Tutorials: Understanding Boolean (Bool) 🎯

beginner
21 min

Swift Tutorials: Understanding Boolean (Bool) 🎯

Introduction to Boolean (Bool) 📝

In Swift, Boolean (or Bool) is a data type that can have only two possible values: true or false. It's primarily used to represent conditions and decisions in your code. Let's dive into understanding this crucial data type!

Why use Boolean? 💡

Boolean values help us create conditional statements, making your code capable of making decisions based on certain conditions. For example, checking if a user has provided valid login credentials or verifying if an array contains a specific value.

Understanding Boolean Values 📝

  • true: Represents a condition that is met or valid.
  • false: Represents a condition that is not met or invalid.

Declaring and Assigning Boolean Variables 📝

To declare and assign a Boolean variable in Swift, simply use the Bool data type followed by the variable name, and then assign a value:

swift
var isLoggedIn: Bool = false

Changing Boolean Values 💡

You can change the value of a Boolean variable by reassigning it with a new value:

swift
isLoggedIn = true

Comparison Operators with Boolean 📝

Swift provides comparison operators to compare two values and return a Boolean result. Here are some examples:

swift
let userAge = 25 let isAdult = userAge >= 18 print(isAdult) // true

Boolean Logical Operators 📝

Logical operators allow you to create more complex conditions by combining multiple Boolean expressions. Here's an overview of logical operators in Swift:

  • && (and): Returns true if both conditions are true.
  • || (or): Returns true if either condition is true.
  • ! (not): Negates the Boolean value.

Examples with Logical Operators 💡

swift
let userName = "John Doe" let isValidUser = userName == "John Doe" && userAge >= 18 print(isValidUser) // true (if userName is "John Doe" and userAge is 18 or more)

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the Swift Boolean data type `Bool` represent?

Let's move on to the next exciting topic, Control Flow Statements. Happy coding! 🚀