0
0
Swiftprogramming~30 mins

Throwing functions with throws in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Throwing functions with throws
📖 Scenario: Imagine you are building a simple app that checks if a password is strong enough. If the password is too short, the app should tell the user with an error.
🎯 Goal: You will create a throwing function that checks password length and throws an error if the password is too short. Then you will call this function and handle the error.
📋 What You'll Learn
Create an enum called PasswordError that conforms to Error with a case tooShort
Create a throwing function called checkPassword that takes a String parameter password
Inside checkPassword, throw PasswordError.tooShort if the password length is less than 8
Call checkPassword inside a do-catch block with the password "abc123"
Print "Password is strong enough" if no error is thrown
Print "Password is too short" if PasswordError.tooShort is caught
💡 Why This Matters
🌍 Real World
Throwing functions are used in apps to handle unexpected problems like invalid input or failed network calls. This helps apps respond gracefully instead of crashing.
💼 Career
Understanding how to write and handle throwing functions is important for Swift developers to build robust and user-friendly applications.
Progress0 / 4 steps
1
Create the PasswordError enum
Create an enum called PasswordError that conforms to Error with a case called tooShort.
Swift
Need a hint?

Use enum PasswordError: Error { case tooShort } to define the error type.

2
Create the throwing function checkPassword
Create a throwing function called checkPassword that takes a String parameter named password. Inside the function, throw PasswordError.tooShort if password.count is less than 8.
Swift
Need a hint?

Define the function with throws and use throw PasswordError.tooShort inside an if check.

3
Call checkPassword inside a do-catch block
Write a do-catch block that calls checkPassword with the password "abc123". In the do block, call checkPassword("abc123"). In the catch block, catch PasswordError.tooShort specifically.
Swift
Need a hint?

Use do { try checkPassword("abc123") ... } catch PasswordError.tooShort { ... } to handle the error.

4
Print the result
Run the program to print the result of the password check. The output should be "Password is too short" because the password "abc123" has less than 8 characters.
Swift
Need a hint?

Run the code and check the console output.