0
0
Swiftprogramming~15 mins

Guard let for early exit in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the optional email variable
Create an optional string variable called email and set it to "user@example.com".
Swift
Need a hint?

Use var email: String? = "user@example.com" to create an optional string variable.

2
Create the minimum length constant
Create a constant called minimumLength and set it to 5.
Swift
Need a hint?

Use let minimumLength = 5 to create a constant.

3
Use guard let to unwrap and check email
Write a function called checkEmail(). Inside it, use guard let to unwrap email into a constant called unwrappedEmail. Also check that unwrappedEmail.count is at least minimumLength. If the check fails, print "Invalid email" and return early.
Swift
Need a hint?

Use guard let unwrappedEmail = email, unwrappedEmail.count >= minimumLength else { print("Invalid email"); return } inside the function.

4
Print valid email after guard let
Inside the checkEmail() function, after the guard let statement, print "Email is valid: <unwrappedEmail>". Then call checkEmail() to run the function.
Swift
Need a hint?

Use print("Email is valid: \(unwrappedEmail)") and call checkEmail().