0
0
Swiftprogramming~15 mins

Try? for optional result in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using try? for Optional Result in Swift
📖 Scenario: Imagine you are building a simple app that reads numbers from text inputs and converts them to integers. Sometimes the input might not be a valid number, and you want to handle this safely without crashing the app.
🎯 Goal: You will learn how to use try? in Swift to safely attempt an operation that might fail and get an optional result instead of a crash.
📋 What You'll Learn
Create a function that throws an error if the input string is not a valid number
Use try? to call this function and get an optional integer
Print the optional result to see if the conversion succeeded or failed
💡 Why This Matters
🌍 Real World
Apps often need to convert user input to numbers safely. Using <code>try?</code> helps avoid crashes when input is invalid.
💼 Career
Understanding error handling and optionals is essential for Swift developers building robust iOS apps.
Progress0 / 4 steps
1
Create a throwing function to convert string to integer
Write a function called convertToInt that takes a String parameter named input and returns an Int. The function should throw an error if the string cannot be converted to an integer. Define an enum ConversionError with a case invalidNumber to represent this error.
Swift
Need a hint?

Use Int(input) to try converting the string. If it fails, throw ConversionError.invalidNumber.

2
Use try? to call the throwing function safely
Create a constant called result and assign it the value of calling convertToInt with the string "123" using try? to handle the error as an optional.
Swift
Need a hint?

Use let result = try? convertToInt(input: "123") to get an optional integer.

3
Try converting an invalid string with try?
Create a constant called invalidResult and assign it the value of calling convertToInt with the string "abc" using try?.
Swift
Need a hint?

Use let invalidResult = try? convertToInt(input: "abc") to get nil for invalid input.

4
Print the optional results
Print the values of result and invalidResult using print statements to see the optional results.
Swift
Need a hint?

Use print(result) and print(invalidResult) to see the optional values.