Control Flow
Control flow is a fundamental concept in programming that allows you to execute different blocks of code based on certain conditions or repeatedly. This section will introduce you to the key control flow constructs in Swift, including loops and conditionals.
Conditional Statements
If-Else Statement
The if-else
statement allows you to execute different code blocks based on a condition.
if age >= 18 {
print("You are eligible to vote.")
} else {
print("You are not eligible to vote.")
}
Switch Statement
The switch
statement is used for multiple conditions and is more readable than nested if-else
statements.
switch grade {
case "A":
print("Excellent!")
case "B":
print("Good!")
default:
print("Keep trying!")
}
Loops
For Loop
The for
loop is used for iterating over a sequence, like an array or a range.
for i in 1...5 {
print("Iteration \(i)")
}
While Loop
The while
loop continues as long as a condition is true.
while count < 5 {
print("Count is \(count)")
count += 1
}
Repeat-While Loop
The repeat-while
loop is similar to the while
loop but checks the condition after the loop is executed.
repeat {
print("This will run at least once.")
} while false
Conclusion
Understanding control flow in Swift is crucial for creating dynamic and interactive programs. The if-else
and switch
statements allow you to make decisions in your code, while loops like for
, while
, and repeat-while
let you execute code repeatedly.
Book a conversation with us for personalize training today!