0
0
Swiftprogramming~5 mins

Error protocol conformance in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aclass
Benum
Ctuple
Darray
What keyword is used to indicate a function can throw an error in Swift?
Aerror
Bthrowable
Cthrows
Dtry
What protocol must a type conform to in order to be thrown as an error?
ACatchable
BThrowable
CException
DError
Which of these is a valid way to define a custom error in Swift?
Aenum MyError: Error { case invalidInput }
Bstruct MyError { case invalidInput }
Cclass MyError { func error() {} }
Dlet MyError = "error"
What happens if you try to throw a String directly in Swift?
ACompilation error
BRuns without error
CRuntime error
DWarning only
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.