Guard for early exit pattern
📖 Scenario: You are writing a simple Swift program that checks user input for a valid age before continuing. This is like checking if someone is old enough to enter a club. If the age is not valid, the program should stop early and show a message.
🎯 Goal: Build a Swift program that uses the guard statement to check if an age is valid (between 18 and 99). If the age is invalid, the program should exit early with a message. Otherwise, it should print a welcome message.
📋 What You'll Learn
Create a variable called
ageInput with the value "25" (a string).Create a variable called
age that tries to convert ageInput to an integer using Int(ageInput).Use a
guard statement to check if age is not nil and between 18 and 99 inclusive.If the
guard condition fails, print "Invalid age. Access denied." and exit the function early.If the
guard condition passes, print "Welcome! You are allowed access.".💡 Why This Matters
🌍 Real World
Checking user input early is common in apps to avoid errors and improve user experience, like verifying age for age-restricted content.
💼 Career
Using <code>guard</code> for early exit is a key Swift skill for writing safe, readable, and maintainable code in iOS app development.
Progress0 / 4 steps