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 tooShortCreate a throwing function called
checkPassword that takes a String parameter passwordInside
checkPassword, throw PasswordError.tooShort if the password length is less than 8Call
checkPassword inside a do-catch block with the password "abc123"Print
"Password is strong enough" if no error is thrownPrint
"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