0
0
Swiftprogramming~15 mins

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

Choose your learning style9 modes available
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
1
Create the initial age input
Create a variable called ageInput and set it to the string "25".
Swift
Need a hint?

Use var ageInput = "25" to create the variable.

2
Convert the input string to an integer
Create a variable called age and set it to Int(ageInput) to convert the string to an integer.
Swift
Need a hint?

Use var age = Int(ageInput) to convert the string to an integer.

3
Use guard to check age validity
Write a guard statement to check if age is not nil and between 18 and 99 inclusive. Use else to print "Invalid age. Access denied." and return early.
Swift
Need a hint?

Use guard let validAge = age to unwrap the optional, then check the range with validAge >= 18 and validAge <= 99.

4
Print welcome message after guard
After the guard statement, print "Welcome! You are allowed access.".
Swift
Need a hint?

Use print("Welcome! You are allowed access.") after the guard block.