Recall & Review
beginner
What does it mean for a type to conform to the
Error protocol in Swift?Conforming to the
Error protocol means the type can be used to represent errors that can be thrown and caught in Swift's error handling system.Click to reveal answer
beginner
How do you declare a custom error type in Swift?
You declare an enum or struct that conforms to the
Error protocol. For example:<br>enum MyError: Error { case badInput case networkFailure }Click to reveal answer
intermediate
Can any type conform to the
Error protocol in Swift?Yes, any type (enum, struct, or class) can conform to
Error. But enums are preferred because they clearly define distinct error cases.Click to reveal answer
intermediate
Why is it useful to conform to the
Error protocol instead of using strings for errors?Conforming to
Error allows Swift's error handling system to work with your errors, enabling throw, try, and catch with type safety and better code clarity.Click to reveal answer
beginner
What happens if you throw a value that does not conform to
Error?Swift will not compile the code because only types conforming to
Error can be thrown. This ensures only valid error types are used.Click to reveal answer
Which Swift type is most commonly used to define custom errors conforming to
Error?✗ Incorrect
Enums are preferred for defining custom errors because they clearly list distinct error cases.
What keyword is used to indicate a function can throw an error in Swift?
✗ Incorrect
The
throws keyword marks a function that can throw an error.What protocol must a type conform to in order to be thrown as an error?
✗ Incorrect
Only types conforming to the
Error protocol can be thrown.Which of these is a valid way to define a custom error in Swift?
✗ Incorrect
An enum conforming to
Error with cases is the correct way.What happens if you try to throw a String directly in Swift?
✗ Incorrect
Only types conforming to
Error can be thrown, so throwing a String causes a compile error.Explain how to create and use a custom error type in Swift that conforms to the Error protocol.
Think about how you list error cases and how Swift expects errors to be thrown and caught.
You got /3 concepts.
Why is conforming to the Error protocol important for error handling in Swift?
Consider what Swift's error system requires to work properly.
You got /3 concepts.