Guard let for early exit
📖 Scenario: Imagine you are writing a simple Swift program that processes user input for an app. The app needs to check if the user has entered a valid email address before continuing.
🎯 Goal: You will build a Swift program that uses guard let to safely unwrap an optional email string and exit early if the email is missing or empty.
📋 What You'll Learn
Create an optional string variable called
email with the value "user@example.com".Create a constant called
minimumLength and set it to 5.Use a
guard let statement to unwrap email and check that its length is at least minimumLength.If the
guard let condition fails, print "Invalid email" and exit the function early.If the email is valid, print
"Email is valid: <email>".💡 Why This Matters
🌍 Real World
Checking user input safely is very common in apps to avoid crashes and handle errors gracefully.
💼 Career
Understanding optionals and early exit with <code>guard let</code> is essential for Swift developers working on iOS apps.
Progress0 / 4 steps