Challenge - 5 Problems
Swift Rethrowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a rethrowing function with no error
What is the output of this Swift code when the closure does not throw an error?
Swift
func perform(action: () throws -> Void) rethrows { try action() print("Action completed") } try? perform { print("Hello") }
Attempts:
2 left
💡 Hint
Remember that the closure prints first, then the function prints after successful execution.
✗ Incorrect
The closure prints "Hello" first. Since it doesn't throw, the function continues and prints "Action completed".
❓ Predict Output
intermediate2:00remaining
Error propagation in rethrowing function
What happens when the closure passed to this rethrowing function throws an error?
Swift
enum SampleError: Error { case failed } func execute(task: () throws -> Void) rethrows { try task() print("Task done") } try? execute { throw SampleError.failed }
Attempts:
2 left
💡 Hint
The try? converts error to nil and suppresses output after error.
✗ Incorrect
The closure throws an error, so the function does not print "Task done". The try? catches the error silently, so no output appears.
🔧 Debug
advanced2:00remaining
Identify the error in rethrowing function usage
Which option causes a compile-time error in this Swift code?
Swift
func riskyOperation(action: () throws -> Void) rethrows { try action() } func callRisky() { try riskyOperation { print("Running") } }
Attempts:
2 left
💡 Hint
Check if the calling function handles errors properly.
✗ Incorrect
Since 'riskyOperation' is rethrowing and the closure can throw, 'callRisky' must be marked 'throws' or handle the error.
🧠 Conceptual
advanced2:00remaining
Understanding rethrowing function constraints
Which statement about rethrowing functions in Swift is TRUE?
Attempts:
2 left
💡 Hint
Think about when the function propagates errors.
✗ Incorrect
Rethrowing functions only throw errors if the closure they call throws. They do not throw independently.
❓ Predict Output
expert2:00remaining
Output of nested rethrowing functions with error
What is the output of this Swift code snippet?
Swift
enum MyError: Error { case fail } func outer(action: () throws -> Void) rethrows { print("Outer start") try inner(action: action) print("Outer end") } func inner(action: () throws -> Void) rethrows { print("Inner start") try action() print("Inner end") } try? outer { print("Action running") throw MyError.fail }
Attempts:
2 left
💡 Hint
Trace the prints until the error is thrown and stops execution.
✗ Incorrect
The error thrown inside the closure stops execution immediately after "Action running". "Inner end" and "Outer end" are not printed.