Swift Bool
In Swift, Bool is a frozen structure, whose instances are either true or false.
In this tutorial, we will learn how to declare a Bool variable, how to initialize a variable with boolean value, different operations that can be done on boolean values, and how to use a boolean value with conditional statements.
Declare Boolean Variable
To declare a variable to be explicitly Bool, specify Bool keyword after the variable name during the declaration as shown in the following code snippet.
var b: Bool
Now, b
is a variable that holds only boolean values.
We can also initialise the variable with a boolean value, of course either true or false.
var b = true
Now, b
is a boolean value without any explicit declaration, because the first time we stored a value in the variable b
is a boolean value.
Initialize Boolean Variable
To initialize a variable with boolean value, use assignment operator and assign true or false.
var a = true var b = false
Logical Operations
Logical Operations transform one or more boolean values into a resulting boolean value.
Swift supports three Logical Operators. They are
Operator | Name | Description |
---|---|---|
! | Logical NOT Operator. | Takes a single operand and performs negation operation. |
&& | Logical AND Operator. | Takes two operands and returns true only if both the operands are true, else false. |
|| | Logical OR Operator. | Takes two operands and returns true if at least one of the operands is true, else false. |
In the following program, we take two Boolean variables, and perform Logical operations on them.
main.swift
var a = true var b = false print("!a is \(!a)") print("a && b is \(a && b)") print("a || b is \(a || b)")
Output
!a is false a && b is false a || b is true
Boolean Value in Conditional Statements
Boolean value is used to conditionally execute a set of statements in if, if-else, for loop, while loop, etc.
Conclusion
In this Swift Tutorial, we learned what Boolean is in swift, how to declare/initialize a boolean value, how to perform logical operations on boolean values, and how to use them with conditional statements, with the help of examples.