0
0
iOS Swiftmobile~20 mins

Error handling (try, catch, throw) in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Error Handling Demo
This screen lets the user enter a number and tries to convert it to an integer. If the input is invalid, it shows an error message using Swift's try, catch, and throw error handling.
Target UI
-------------------------
| Error Handling Demo   |
-------------------------
| Enter a number:       |
| [______________]     |
| [Convert]            |
|                      |
| Result:              |
|                      |
-------------------------
A TextField for user input of a number
A Convert button below the TextField
When Convert is tapped, try to convert input to Int using a throwing function
If conversion succeeds, show 'Valid number: X' in Result label
If conversion fails, catch the error and show 'Error: Invalid number' in Result label
Use Swift's try, catch, and throw keywords properly
Starter Code
iOS Swift
import SwiftUI

struct ErrorHandlingDemoView: View {
    @State private var userInput = ""
    @State private var resultMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Error Handling Demo")
                .font(.title)

            TextField("Enter a number", text: $userInput)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.numberPad)
                .padding(.horizontal)

            Button("Convert") {
                // TODO: Call the function that tries to convert input
                // and update resultMessage accordingly
            }
            .buttonStyle(.borderedProminent)

            Text("Result: \(resultMessage)")
                .padding()

            Spacer()
        }
        .padding()
    }

    // TODO: Add a throwing function to convert String to Int
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
import SwiftUI

enum ConversionError: Error {
    case invalidNumber
}

struct ErrorHandlingDemoView: View {
    @State private var userInput = ""
    @State private var resultMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Error Handling Demo")
                .font(.title)

            TextField("Enter a number", text: $userInput)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.numberPad)
                .padding(.horizontal)

            Button("Convert") {
                do {
                    let number = try convertToInt(userInput)
                    resultMessage = "Valid number: \(number)"
                } catch {
                    resultMessage = "Error: Invalid number"
                }
            }
            .buttonStyle(.borderedProminent)

            Text("Result: \(resultMessage)")
                .padding()

            Spacer()
        }
        .padding()
    }

    func convertToInt(_ input: String) throws -> Int {
        if let number = Int(input) {
            return number
        } else {
            throw ConversionError.invalidNumber
        }
    }
}

This app screen uses a TextField to get user input as a string. The convertToInt function tries to convert the string to an integer. If it fails, it throws a custom error ConversionError.invalidNumber.

When the user taps the Convert button, the app uses a do-try-catch block to call convertToInt. If conversion succeeds, it updates the result message with the valid number. If it fails, it catches the error and shows an error message.

This demonstrates how to handle errors gracefully in Swift using try, catch, and throw.

Final Result
Completed Screen
-------------------------
| Error Handling Demo   |
-------------------------
| Enter a number:       |
| [12345__________]    |
| [Convert]            |
|                      |
| Result:              |
| Valid number: 12345  |
-------------------------
User types a number in the TextField
User taps Convert button
If input is a valid number, Result label shows 'Valid number: X'
If input is invalid (e.g., letters), Result label shows 'Error: Invalid number'
Stretch Goal
Add a Clear button that resets the input and result message
💡 Hint
Add another Button below Convert that sets userInput and resultMessage to empty strings