0
0
Swiftprogramming~15 mins

Error protocol conformance in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Protocol Conformance in Swift
📖 Scenario: Imagine you are building a simple app that checks user input and reports errors clearly.
🎯 Goal: You will create a custom error type by conforming to the Error protocol, then use it to handle errors in a function.
📋 What You'll Learn
Create an enum called InputError that conforms to the Error protocol
Add two cases to InputError: empty and tooShort
Write a function validateInput(_ input: String) throws that throws InputError.empty if the input is empty
Throw InputError.tooShort if the input length is less than 5 characters
Use a do-catch block to call validateInput and print appropriate messages for each error
💡 Why This Matters
🌍 Real World
Custom error types help apps give clear feedback when something goes wrong, like invalid user input.
💼 Career
Understanding error handling is essential for writing safe and user-friendly Swift applications.
Progress0 / 4 steps
1
Create the InputError enum conforming to Error
Create an enum called InputError that conforms to the Error protocol. Add two cases: empty and tooShort.
Swift
Need a hint?

Use enum InputError: Error to start. Add case empty and case tooShort inside.

2
Write the validateInput function that throws errors
Write a function called validateInput(_ input: String) throws. Inside, throw InputError.empty if input is empty. Throw InputError.tooShort if input.count is less than 5.
Swift
Need a hint?

Use if input.isEmpty to check empty. Use throw InputError.empty inside. Then check input.count < 5 and throw InputError.tooShort.

3
Use do-catch to handle errors from validateInput
Write a do-catch block that calls try validateInput(input) with input set to "Hi". Catch InputError.empty and print "Input is empty". Catch InputError.tooShort and print "Input is too short". Catch any other errors and print "Unknown error".
Swift
Need a hint?

Use do { try validateInput(input) } and multiple catch blocks for each error case. Print messages inside each catch.

4
Print the final output
Run the program and print the output from the do-catch block.
Swift
Need a hint?

The output should be Input is too short because "Hi" has less than 5 characters.