0
0
Swiftprogramming~30 mins

Rethrowing functions in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Rethrowing Functions in Swift
📖 Scenario: Imagine you are building a small app that processes tasks. Some tasks might fail and throw errors. You want to write a function that accepts another function as input and calls it. If the input function throws an error, your function should pass that error up to the caller.
🎯 Goal: You will create a rethrowing function in Swift that calls a throwing function passed as a parameter. This will help you understand how to handle errors in higher-order functions.
📋 What You'll Learn
Create a throwing function called taskThatMightFail that throws an error of type TaskError.
Create a rethrowing function called performTask that accepts a throwing function parameter and rethrows errors.
Call performTask with taskThatMightFail inside a do-catch block to handle errors.
Print "Task succeeded" if no error occurs, or print the error message if it fails.
💡 Why This Matters
🌍 Real World
Rethrowing functions are useful when you write utility functions that call other functions which might throw errors. This helps keep error handling clean and flexible.
💼 Career
Understanding rethrowing functions is important for Swift developers working on apps that handle errors gracefully, such as network requests, file operations, or user input validation.
Progress0 / 4 steps
1
Define the error type and a throwing function
Create an enum called TaskError that conforms to Error with a case failed. Then create a function called taskThatMightFail that throws TaskError.failed.
Swift
Need a hint?

Define an enum for errors and a function that always throws that error.

2
Create a rethrowing function
Create a function called performTask that accepts a parameter task of type () throws -> Void. Mark performTask with rethrows and call task() inside it.
Swift
Need a hint?

Use rethrows to let performTask throw only if task throws.

3
Call the rethrowing function inside a do-catch block
Write a do-catch block where you call performTask with taskThatMightFail as the argument. In the catch block, print "Caught error: \(error)".
Swift
Need a hint?

Use do and catch to handle errors from performTask.

4
Modify the throwing function to sometimes succeed and print success message
Change taskThatMightFail to accept a Boolean parameter shouldFail. If shouldFail is true, throw TaskError.failed, otherwise do nothing. Then call performTask with a closure that calls taskThatMightFail(shouldFail: false). In the do block, print "Task succeeded".
Swift
Need a hint?

Use a closure to call taskThatMightFail with shouldFail: false and print success if no error.