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!
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.
true: Represents a condition that is met or valid.false: Represents a condition that is not met or invalid.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:
var isLoggedIn: Bool = falseYou can change the value of a Boolean variable by reassigning it with a new value:
isLoggedIn = trueSwift provides comparison operators to compare two values and return a Boolean result. Here are some examples:
let userAge = 25
let isAdult = userAge >= 18
print(isAdult) // trueLogical 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.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)What does the Swift Boolean data type `Bool` represent?
Let's move on to the next exciting topic, Control Flow Statements. Happy coding! 🚀