Swift Tutorials: break Statement 🎯

beginner
5 min

Swift Tutorials: break Statement 🎯

Welcome back to CodeYourCraft! Today, we're diving into the Swift world and learning about the break statement. This powerful tool will help you control the flow of your code and make your programs more efficient. Let's get started! 🎉

Understanding the break Statement 📝

The break statement is used to exit a loop prematurely. In other words, it allows you to stop the loop from running any further and continue with the rest of your code.

swift
for i in 1...10 { if i == 5 { break } print(i) }

In this example, we have a for loop that runs from 1 to 10. Inside the loop, we have an if statement that checks if the current number (i) is equal to 5. If it is, the break statement is executed, and the loop is exited immediately.

Why Use break? 💡

The break statement is useful when you want to terminate a loop based on a specific condition. For instance, you might have a loop that searches for a specific item in an array, and once the item is found, you no longer need to continue searching. By using break, you can save processing time and resources.

Advanced Example 🎯

Let's consider a real-world example where we have a function that checks if a given password meets certain criteria. If the password is valid, the function returns true; if not, it continues checking until a valid password is found or a maximum number of attempts is reached.

swift
func checkPassword(password: String, attempts: Int) -> Bool { for char in password { if char.isUppercase, attempts > 0 { attempts -= 1 continue } else if char.isLowercase, attempts > 0 { attempts -= 1 continue } else if char.isDigit, attempts > 0 { attempts -= 1 continue } else if char == "@", attempts > 0 { attempts -= 1 continue } else if char == "#", attempts > 0 { attempts -= 1 continue } if attempts == 0 { print("You have reached the maximum number of attempts.") return false } } print("Valid password.") return true }

In this example, we have a checkPassword function that takes a password and the number of attempts as parameters. Inside the function, we have a for loop that iterates through each character in the password. We use continue to skip certain characters based on the given criteria (at least one uppercase, one lowercase, one digit, and either @ or #). If a valid password is not found after the maximum number of attempts, the function returns false, and the loop is exited using the break statement.

Quiz Time 📝

We hope you enjoyed learning about the break statement in Swift! In the next lesson, we'll dive into another powerful tool: the continue statement. Until then, happy coding! 🤘