Control flow
Control flow in Swift refers to the mechanisms used to control the sequence of events or the flow of execution in a program. Swift provides various control flow constructs like loops, conditionals, and branches.
Conditional Statements
If Statement
The if statement is used to conditionally execute a block of code.
let x = 10
if x > 5 {
print("x is greater than 5")
}
If-Else Statement
You can use the else clause to execute code when the condition is not met.
if x > 5 {
print("x is greater than 5")
} else {
print("x is less than or equal to 5")
}
If-Else If-Else Statement
You can chain multiple if conditions using else if.
if x > 10 {
print("x is greater than 10")
} else if x > 5 {
print("x is greater than 5 but less than or equal to 10")
} else {
print("x is less than or equal to 5")
}
Switch Statement
Swift's switch statement is powerful and can match against a variety of conditions, including ranges and tuples.
switch x {
case 0:
print("Zero")
case 1...9:
print("Single digit")
case 10:
print("It's ten")
default:
print("More than ten")
}
Loops
For-In Loop
Used for iterating over sequences like arrays, dictionaries, ranges, etc.
for i in 1...3 {
print(i)
}
for element in [1, 2, 3] {
print(element)
}
for (key, value) in ["One": 1, "Two": 2] {
print("\(key): \(value)")
}
While Loop
Executes a block of code as long as a condition is true.
var i = 1
while i <= 3 {
print(i)
i += 1
}
Repeat-While Loop
Similar to the while loop but evaluates the condition after executing the code block, guaranteeing at least one execution.
var i = 1
repeat {
print(i)
i += 1
} while i <= 3
Control Transfer Statements
Continue
Used within a loop to skip the current iteration.
for i in 1...5 {
if i == 3 {
continue
}
print(i)
}
Break
Used to exit a loop or a switch statement immediately.
for i in 1...5 {
if i == 3 {
break
}
print(i)
}
Labeled Statements
You can label loops and conditional statements, and then use break or continue with those labels for better control.
outerLoop: for i in 1...3 {
for j in 1...3 {
if j == 2 {
break outerLoop
}
print("\(i), \(j)")
}
}
Fallthrough
In Swift, switch cases don't fall through by default. Use the fallthrough keyword to achieve C-style fallthrough behavior.
switch x {
case 10:
print("It's ten")
fallthrough
case 1...9:
print("Single digit")
default:
print("More than ten")
}
These are the fundamental control flow constructs in Swift, allowing for powerful and flexible programming.