Welcome back to CodeYourCraft! Today, we're diving into Swift's Labeled Statements. Let's get started! 🎉
Labeled Statements are a way to give a name to a specific part of your Swift code. This can be incredibly useful for navigating complex control structures like loops and functions.
myLoop: for i in 1...10 {
// Your code here
if i == 5 {
break myLoop // Exit the loop at this point
}
}In the example above, myLoop is a label we've given to our for loop. We can use this label to break out of the loop at a specific point, like when i equals 5.
We can also use labels with the continue statement to skip over the current iteration of a loop.
myLoop: for i in 1...10 {
if i == 3 {
continue myLoop // Skip the current iteration if i equals 3
}
print(i)
}In this example, when i equals 3, the loop skips that iteration and moves on to the next one.
You can even have multiple labeled statements nested within each other. This allows for more complex flow control in your Swift code.
outerLoop: for i in 1...10 {
innerLoop: for j in 1...10 {
if i == 5 && j == 5 {
break outerLoop // Exit both loops when i equals 5 and j equals 5
}
print("i: \(i), j: \(j)")
}
}In the example above, we have an outerLoop that contains an innerLoop. When both i and j equal 5, we break out of both loops.
What is the purpose of a labeled statement in Swift?
That's it for today! We hope you found this lesson on Labeled Statements in Swift helpful. Stay tuned for more Swift tutorials on CodeYourCraft. Happy coding! 💻🌟