Recall & Review
beginner
What does it mean when a function is marked as
rethrows in Swift?A
rethrows function can only throw an error if one of the functions it calls (passed as parameters) throws an error. It does not throw errors on its own.Click to reveal answer
beginner
How do you declare a function that can rethrow errors from a closure parameter?
You add the
rethrows keyword after the parameter list. For example: <br>func perform(action: () throws -> Void) rethrows { try action() }Click to reveal answer
beginner
Can a
rethrows function throw an error by itself without calling a throwing function?No. A
rethrows function can only throw if the closure or function it calls throws. It cannot throw errors independently.Click to reveal answer
intermediate
Why use
rethrows instead of throws in Swift?Using
rethrows makes your function safer and clearer. It only throws errors if the passed-in function throws, so callers don’t have to handle errors if the passed function doesn’t throw.Click to reveal answer
intermediate
Example: What is the output of this Swift code?<br>
func callTwice(action: () throws -> Void) rethrows { try action(); try action() }<br>try? callTwice { print("Hello") }Output:<br>Hello<br>Hello<br><br>Explanation: The closure does not throw, so
callTwice runs both times and prints "Hello" twice without error.Click to reveal answer
What keyword do you use to declare a function that only throws if a passed-in function throws?
✗ Incorrect
The
rethrows keyword means the function only throws if the function it calls throws.Can a
rethrows function throw an error on its own without calling a throwing function?✗ Incorrect
A
rethrows function cannot throw errors by itself; it only throws if the passed-in function throws.Which of these is a valid declaration of a rethrowing function?
✗ Incorrect
Only option A correctly declares a rethrowing function that calls a throwing closure.
What happens if you call a
rethrows function with a non-throwing closure?✗ Incorrect
If the closure does not throw, the
rethrows function runs without throwing.Why might you prefer
rethrows over throws?✗ Incorrect
rethrows lets the function throw only if the passed-in function throws, making error handling conditional.Explain in your own words what a rethrowing function is and why it is useful.
Think about when the function throws errors and when it doesn't.
You got /3 concepts.
Write a simple Swift function that uses
rethrows to call a throwing closure twice.Use the example: func callTwice(action: () throws -> Void) rethrows { try action(); try action() }
You got /3 concepts.