0
0
Swiftprogramming~30 mins

Do-try-catch execution flow in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Do-try-catch Execution Flow in Swift
📖 Scenario: Imagine you are writing a simple Swift program that reads a number from a string and handles errors if the string is not a valid number.
🎯 Goal: You will build a Swift program that uses do-try-catch to safely convert a string to a number and handle possible errors.
📋 What You'll Learn
Create a function that throws an error if the string is not a valid number
Use a do block with try to call the function
Add catch blocks to handle errors
Print the result or error message
💡 Why This Matters
🌍 Real World
Handling errors when converting user input or data from files is very common in apps and programs.
💼 Career
Understanding <code>do-try-catch</code> is essential for Swift developers to write robust and crash-free code.
Progress0 / 4 steps
1
Create a throwing function
Write a function called convertToInt that takes a String parameter named input and returns an Int. The function should throw an error of type ConversionError.invalidNumber if the string cannot be converted to an integer. Define the ConversionError enum with a case invalidNumber.
Swift
Need a hint?

Use guard let to try converting the string to Int. If it fails, throw the error.

2
Set up the input string
Create a constant called inputString and set it to the string "123a".
Swift
Need a hint?

Use let inputString = "123a" to create the string.

3
Use do-try-catch to convert the string
Write a do block that tries to convert inputString to an integer using try convertToInt(input: inputString). Store the result in a constant called number. Add a catch block that catches ConversionError.invalidNumber and prints "Invalid number format.". Add a general catch block that prints "Unknown error.".
Swift
Need a hint?

Use do { let number = try convertToInt(input: inputString) } and add catch blocks for errors.

4
Print the final output
Run the program and observe the output printed by the do-try-catch block.
Swift
Need a hint?

The program should print Invalid number format. because the string contains a letter.