0
0
Swiftprogramming~5 mins

Rethrowing functions in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Acatch
Brethrows
Ctry
Dthrows
Can a rethrows function throw an error on its own without calling a throwing function?
AYes, always
BOnly if marked with <code>throws</code>
CNo, never
DOnly if the closure is non-throwing
Which of these is a valid declaration of a rethrowing function?
Afunc example(action: () -> Void) throws { action() }
Bfunc example() rethrows { throw Error() }
Cfunc example() throws { }
Dfunc example(action: () throws -> Void) rethrows { try action() }
What happens if you call a rethrows function with a non-throwing closure?
AIt runs without throwing
BIt throws an error
CYou must use try
DIt crashes
Why might you prefer rethrows over throws?
ATo allow throwing only when needed
BTo avoid using try
CTo force error handling always
DTo catch errors automatically
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.