Contents
Swift Control Flow
Decision-Making Statements in Swift
Decision-making statements in Swift allow the program to choose a specific block of code to execute based on a given condition. These statements evaluate conditions and return a boolean value (true
or false
). If the condition is true
, the associated block of code is executed; otherwise, an alternate block is executed. Swift supports five types of decision-making statements:
1. Simple if
2. if-else
3. if-else if-else
4. Nested if
5. Switch
Simple if Statement
In Swift, the if
statement is used to execute a block of code based on the evaluation of one or more conditions. This type of statement is often referred to as a branch statement. It allows the program to “branch” and execute specific blocks of code when certain conditions are met.
For example, consider a real-life scenario: you plan to visit a market, and your parent instructs you, “If the plastic containers are on sale, buy two containers.” This is a conditional statement where the action, “buy two containers,” will only occur if the condition, “plastic containers are on sale,” is true.
Conditional statements are essential in programming as they help introduce logic and decision-making into the code.
Syntax:
if (condition) {
// Body of the if statement
}
- The
if
statement evaluates the condition inside the parentheses()
. - If the condition evaluates to
true
, the block of code inside the curly braces{}
is executed. - If the condition evaluates to
false
, the block of code is skipped, and the control moves to the next statement.
Example 1: Basic if
Statement
// Swift program demonstrating the if statement
let val = 30
// Checking if the number is greater than zero
if (val > 0) {
// Body of the if statement
print("The given number is positive.")
}
// Statement after the if statement (always executed)
print("Learning if statement in Swift.")
Output:
The given number is positive.
Learning if statement in Swift.
Explanation:
- A variable
val
is declared with a value of30
. - The condition
val > 0
is evaluated. Since30 > 0
, the condition istrue
. - The code inside the
if
block is executed, printing:"The given number is positive."
- The statement after the
if
block,"Learning if statement in Swift."
, is executed regardless of the condition’s result. - If
val
were set to-20
, the condition would befalse
, and only the statement outside theif
block would be executed.
Example 2: Checking Eligibility
This person is eligible for voting.
Only 18+ people are eligible for voting.
Output:
Integer Type Min Max
UInt8 0 255
UInt16 0 65535
UInt32 0 4294967295
UInt64 0 18446744073709551615
Int8 -128 127
Int16 -32768 32767
Int32 -2147483648 2147483647
Int64 -9223372036854775808 9223372036854775807
Example 3: Using Multiple if
Statements
You can use multiple if
statements to check independent conditions instead of using if-else
.
// Swift program demonstrating multiple if statements
let number = 9
// First condition
if (number % 2 == 0) {
print("\(number) is an even number")
}
// Second condition
if (number % 2 != 0) {
print("\(number) is an odd number")
}
// Third condition
if (number == 9) {
print("Given number \(number) is equal to the given condition number")
}
Output:
9 is an odd number
Given number 9 is equal to the given condition number
Explanation:
- The first
if
checks if the number is even (number % 2 == 0
), which is false for9
, so this block is skipped. - The second
if
checks if the number is odd (number % 2 != 0
), which is true for9
, so it prints:"9 is an odd number."
- The third
if
checks if the number equals9
, which is true, so it prints:"Given number 9 is equal to the given condition number."
If-else Statement
In Swift, the if-else
statement is used to execute a block of code based on a condition and provide an alternative block of code to execute when the condition is not met. This allows programmers to handle conditional logic effectively, ensuring that the program can make decisions dynamically.
For example, imagine you’re at the market, and your parent says, “If biscuits are on sale, buy biscuits; otherwise, buy chips.” This is a typical if-else
condition where one action is executed if the condition is true, and an alternative action is executed if the condition is false.
Syntax of the if-else
Statement
if (condition) {
// Body of the if statement
} else {
// Body of the else statement
}
- The
if
condition is evaluated. - If the condition evaluates to
true
, the code inside theif
block is executed. - If the condition evaluates to
false
, the code inside theelse
block is executed. - The program then continues with the code after the
if-else
block.
Examples:
// Swift program to demonstrate the use of if-else statement
// Declare and initialize a variable
let val = 40
// Check if the number is equal to 40
if (val == 40) {
print("Both the numbers are equal")
} else {
print("Both the numbers are not equal")
}
// Code after if…else statement
// This statement is always executed
print("Learning if…else statement in Swift.")
Output:
Both the numbers are equal
Learning if…else statement in Swift.
Explanation:
- The variable
val
is initialized with a value of40
. - The condition
val == 40
evaluates totrue
, so the code inside theif
block is executed, printing:"Both the numbers are equal"
. - The
else
block is skipped. - The statement after the
if-else
block,"Learning if…else statement in Swift."
, is executed regardless of the condition. - If
val
were set to45
, the condition would evaluate tofalse
, and the output would change to:
Both the numbers are not equal
Learning if…else statement in Swift.
Example 2: Checking Voting Eligibility
// Swift program to demonstrate the use of if-else statement
// Declare and initialize a variable
let age = 80
// Checking if age is greater than or equal to 18
if (age >= 18) {
print("This person is eligible for voting")
} else {
// Executes when the condition is false
print("This person is not eligible for voting")
}
// Code after if…else statement
print("Only 18+ people are eligible for voting")
Output:
This person is eligible for voting
Only 18+ people are eligible for voting
Explanation:
- The variable
age
is initialized with80
. - The condition
age >= 18
evaluates totrue
, so the code inside theif
block is executed, printing:"This person is eligible for voting"
. - The
else
block is skipped. - The final statement after the
if-else
block is executed:"Only 18+ people are eligible for voting"
. - If
age
were set to16
, the output would be:
This person is not eligible for voting
Only 18+ people are eligible for voting
If-else-if Statement
In Swift, the if-else if-else
statement allows you to evaluate multiple conditions and execute the code block corresponding to the first true condition. If none of the conditions are satisfied, the else
block executes by default.
Syntax
if (condition1) {
// Block of code for condition1
} else if (condition2) {
// Block of code for condition2
} else if (condition3) {
// Block of code for condition3
}
.
.
.
else {
// Block of code for all other cases
}
- The program checks each condition in sequence.
- The first condition that evaluates to
true
will execute its associated block of code. - If none of the conditions are true, the
else
block is executed.
Example 1: Grading System
let number = 85
if (number >= 90) {
print("Grade A")
} else if (number >= 75) {
print("Grade B")
} else if (number >= 60) {
print("Grade C")
} else {
print("Grade D")
}
Output:
Grade B
Explanation:
- The variable
number
is assigned the value85
. - The first condition,
number >= 90
, evaluates tofalse
. - The second condition,
number >= 75
, evaluates totrue
. - The program executes the code block associated with
number >= 75
, printing:"Grade B"
. - No further conditions are evaluated because one has already been satisfied.
Example 2: Checking Specific Values
let number = 20
// Condition 1
if (number == 10) {
print("Number is 10")
}
// Condition 2
else if (number == 15) {
print("Number is 15")
}
// Condition 3
else if (number == 20) {
print("Number is 20")
}
// Default case
else {
print("Number is not present")
}
Output:
Number is 20
Explanation:
- The variable
number
is initialized with the value20
. - The first condition,
number == 10
, evaluates tofalse
. - The second condition,
number == 15
, also evaluates tofalse
. - The third condition,
number == 20
, evaluates totrue
, so the corresponding code block executes, printing:"Number is 20"
.
Nested if-else Statement
In Swift, a nested if-else
statement occurs when an if
or else
block contains another if-else
statement inside it. This structure is used when multiple levels of conditions need to be checked. The outer if
condition determines if the inner if-else
will be executed.
Syntax:
// Outer if condition
if (condition1) {
// Inner if condition
if (condition2) {
// Block of Code for condition2
} else {
// Block of Code if condition2 is false
}
} else {
// Inner if condition
if (condition3) {
// Block of Code for condition3
} else {
// Block of Code if condition3 is false
}
}
- If
condition1
istrue
, the outerif
block is executed, and the program checkscondition2
. - If
condition1
isfalse
, the program moves to the outerelse
block and evaluatescondition3
. - Additional layers of
if-else
can be added as needed.
Example 1: Finding the Greatest Value
import Swift
var a = 100
var b = 200
var c = 300
// Outer if statement
if (a > b) {
// Inner if statement
if (a > c) {
// Statement 1
print("100 is Greater")
} else {
// Statement 2
print("300 is Greater")
}
} else {
// Inner if statement
if (b > c) {
// Statement 3
print("200 is Greater")
} else {
// Statement 4
print("300 is Greater")
}
}
Output:
300 is Greater
Explanation:
1. The outer if condition checks whether a > b. Since 100 > 200 is false, the program skips to the else block.
2. Inside the else block, the inner if checks whether b > c. Since 200 > 300 is also false, the program executes the inner else block.
3. The inner else block prints “300 is Greater” because c has the highest value.
Example 2: Checking Number Properties
import Swift
var number = 5
// Outer if statement
if (number >= 0) {
// Inner if statement
if (number == 0) {
// Statement 1
print("Number is 0")
} else {
// Statement 2
print("Number is greater than 0")
}
} else {
// Statement 3
print("Number is smaller than 0")
}
Output:
Number is greater than 0
Switch Statement
In Swift, a switch
statement allows the program to control its flow based on the value of a variable. Once a matching condition is found, the corresponding block is executed, and the control exits the switch
block. A default
case handles values that do not match any condition, though it’s optional if the switch
is exhaustive. Omitting a default
in a non-exhaustive switch
results in a compile-time error.
Syntax:
var myVariable = value
switch myVariable {
case condition1:
expression1
fallthrough // Optional
case condition2:
expression2
fallthrough // Optional
...
default: // Optional if the switch is exhaustive
expression
}
Why Use Switch Statements?
Switch statements provide a cleaner and more readable alternative to multiple if-else
statements. They are especially useful when evaluating a variable against multiple cases.
Example 1: Basic Switch Statement
// Example: Print a string based on a character
var myCharacter = "B"
switch myCharacter {
case "A":
print("Apple")
case "B":
print("Boy")
case "C":
print("Cat")
case "D":
print("Dog")
default:
print("Invalid")
}
Output:
Boy
Fallthrough Statement
The fallthrough
keyword forces the execution to proceed to the next case, regardless of whether its condition matches.
Example: Using Fallthrough
var myCharacter = "B"
switch myCharacter {
case "A":
print("Apple")
case "B":
print("Boy")
fallthrough
case "C":
print("Cat")
case "D":
print("Dog")
default:
print("Invalid")
}
Output:
Boy
Cat
No Implicit Fallthrough
Unlike other languages like C, Swift doesn’t allow implicit fallthrough between cases. Each case
must contain an executable body, or the compiler will raise an error.
Example:
var myCharacter = "B"
switch myCharacter {
case "A":
print("Apple")
case "B":
// Missing body
case "C":
print("Cat")
case "D":
print("Dog")
default:
print("Invalid")
}
Error:
'case' label in a 'switch' should have at least one executable statement
Interval Matching
Swift enables interval-based matching within case
conditions.
Example:
var myInteger = 18
switch myInteger {
case 2:
print("Equal to 2")
case 3..<5:
print("Between 3 and 5")
case 6..<10:
print("Between 6 and 10")
case 11..<22:
print("Between 11 and 22")
default:
print("Invalid")
}
Output:
Between 11 and 22
Tuple Matching
Switch statements can evaluate tuples to test multiple values simultaneously. An underscore (_
) serves as a wildcard.
Example:
var myTuple = (4, 10)
switch myTuple {
case (2, 3):
print("First case gets executed")
case (1...3, 5...11):
print("Second case gets executed")
case (1...5, 8...13):
print("Third case gets executed")
case (11...13, 15...18):
print("Fourth case gets executed")
default:
print("Invalid")
}
Output:
Third case gets executed
Value Binding
Switch statements allow temporary variables to be declared in case
conditions. These variables are accessible only within their respective case blocks.
Example:
var myTuple = (2, 4, 6)
switch myTuple {
case (let myElement1, 3, 6):
print("myElement1 is \(myElement1)")
case (let myElement1, let myElement2, 6):
print("myElement1 is \(myElement1), myElement2 is \(myElement2)")
case (let myElement1, let myElement2, let myElement3):
print("myElement1 is \(myElement1), myElement2 is \(myElement2), myElement3 is \(myElement3)")
}
Output:
myElement1 is 2, myElement2 is 4
Using where
Clause in a Switch Statement
The where
clause adds additional conditions to a case
.
Example:
var myTuple = (20, 10)
switch myTuple {
case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
print("myElement1 is thrice of myElement2")
case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
print("myElement1 is twice of myElement2")
case let (myElement1, myElement2) where myElement1 == myElement2:
print("myElement1 is equal to myElement2")
default:
print("Invalid")
}
Output:
myElement1 is twice of myElement2
Compound Cases
Swift allows multiple conditions to share a single case body by separating them with commas.
Example:
var myCharacter = "B"
switch myCharacter {
case "A", "B":
print("Either Apple or Boy")
case "C":
print("Cat")
case "D":
print("Dog")
default:
print("Invalid")
}
Output:
Either Apple or Boy
Loops
In general, loops are used for iteration, which means repeating a set of instructions. With loops, we can execute tasks multiple times, as required. A loop can run indefinitely until its specified condition is no longer satisfied. Typically, we define a condition to terminate the loop. For instance, if we want to display “Hello World” 100 times, we use a loop and specify a condition such as n <= 100
. The loop will terminate when the condition is no longer met.
Types of Loops in Swift
1. for-in loop
2. while loop
3. repeat-while loop
1. for-in Loop: The for-in
loop is used for iterating over a sequence, such as arrays, dictionaries, ranges, or sets. Unlike an if
statement, which executes a block of code only once if a condition is met, the for-in
loop repeatedly executes the block as long as the condition is satisfied.
Syntax:
for item in range {
// Statements
}
Example:
// Swift program to find if a number is a perfect number
// Declaring variables
var number = 6
var sum = 0
// Iterating to find divisors of the number
for i in 1...(number - 1) {
if number % i == 0 {
sum += i
}
}
// Checking if the sum equals the number
if sum == number {
print("The given number is a perfect number")
} else {
print("The given number is not a perfect number")
}
Output:
The given number is a perfect number
2. While Loop: while
loop repeatedly executes a block of code as long as the specified condition evaluates to true
. Unlike the for-in
loop, the while
loop requires explicit initialization, condition checking, and variable updates.
Syntax:
while condition {
// Statements
increment/decrement
}
Example:
// Swift program to calculate the factorial of a number
// Declaring variables
var num = 5
var factorial = 1
var i = 1
// Iterating to calculate factorial
while i <= num {
factorial *= i
i += 1
}
print("The factorial of the given number is \(factorial)")
Output:
The factorial of the given number is 120
3. Repeat-While Loop: The repeat-while
loop, similar to the do-while
loop in C, executes the block of code at least once before evaluating the condition. It is also referred to as an exit-controlled loop.
Syntax:
repeat {
// Statements
} while condition
Example:
// Swift program to demonstrate repeat-while loop
// Declaring variables
var start = 1
let limit = 10
// Iterating using repeat-while loop
repeat {
print(start)
start += 1
} while start <= limit
Output:
1
2
3
4
5
6
7
8
9
10
Break Statement
The break
statement is a control statement used to immediately terminate the execution of the current loop or switch statement. When the break
condition is met, the loop stops its iterations, and control passes to the first statement following the loop. In simpler terms, the break
statement halts the current program flow based on specified conditions. It can be used within loops or switch statements to terminate execution earlier, especially when the number of iterations isn’t predetermined or depends on dynamic conditions.
Syntax:
break
1. for-in Loop: The for-in
loop in Swift iterates over a sequence, such as a range, array, or string. The break
statement can terminate the loop when a specific condition is satisfied.
Syntax:
for item in sequence {
// Code block
if condition {
break
}
}
Example:
// Swift program demonstrating the use of break in a for-in loop
print("Numbers in the range:")
// Loop from 1 to 10
for number in 1...10 {
if number == 7 {
break
}
print(number)
}
Output:
Numbers in the range:
1
2
3
4
5
6
2. While Loop: The while
loop runs as long as the given condition is true. The break
statement can be used to terminate the loop based on an additional condition.
Syntax:
while condition {
// Code block
if condition {
break
}
}
Example:
// Swift program demonstrating the use of break in a while loop
var count = 1
// Loop to print the first 4 multiples of 3
while count <= 10 {
print("3 x \(count) = \(3 * count)")
if count == 4 {
break
}
count += 1
}
Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3. Nested Loops: The break
statement can also be used in nested loops to terminate only the inner loop or control the flow of nested structures.
Syntax:
for item1 in sequence1 {
for item2 in sequence2 {
if condition {
break
}
}
}
Example:
// Swift program demonstrating break in nested loops
for outer in 1...3 {
for inner in 1...3 {
if outer == 2 {
break
}
print("Outer: \(outer), Inner: \(inner)")
}
}
Output:
Outer: 1, Inner: 1
Outer: 1, Inner: 2
Outer: 1, Inner: 3
Outer: 3, Inner: 1
Outer: 3, Inner: 2
Outer: 3, Inner: 3