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:
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
✗ 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?
Aerror
Bthrowable
Cthrows
Dtry
✗ 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?
ACatchable
BThrowable
CException
DError
✗ 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?
Aenum MyError: Error { case invalidInput }
Bstruct MyError { case invalidInput }
Cclass MyError { func error() {} }
Dlet MyError = "error"
✗ Incorrect
An enum conforming to Error with cases is the correct way.
What happens if you try to throw a String directly in Swift?
ACompilation error
BRuns without error
CRuntime error
DWarning only
✗ 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.
Practice
(1/5)
1. What is the main purpose of the Error protocol in Swift?
easy
A. To create network connections
B. To handle user interface events
C. To manage memory allocation automatically
D. To define custom error types that can be thrown and caught
Solution
Step 1: Understand the role of the Error protocol
The Error protocol is designed to let developers define their own error types in Swift.
Step 2: Identify the purpose of custom error types
Custom error types allow throwing and catching specific errors in code, improving error handling.
Final Answer:
To define custom error types that can be thrown and caught -> Option D
Quick Check:
Error protocol = custom error types [OK]
Hint: Error protocol is for creating your own error types [OK]
Common Mistakes:
Confusing Error protocol with UI or memory management
Hint: Add ': Error' after enum name to conform [OK]
Common Mistakes:
Omitting ': Error' conformance
Using raw value types without conforming to Error
Confusing enum raw types with protocol conformance
3. What will be the output of the following Swift code?
enum FileError: Error {
case notFound
case unreadable
}
func readFile(_ name: String) throws -> String {
if name == "missing.txt" {
throw FileError.notFound
}
return "File content"
}
do {
let content = try readFile("missing.txt")
print(content)
} catch FileError.notFound {
print("File not found error caught")
} catch {
print("Other error")
}
medium
A. File not found error caught
B. File content
C. Other error
D. No output
Solution
Step 1: Analyze the function behavior
The function throws FileError.notFound when the filename is "missing.txt".
Step 2: Check the do-catch block
The catch block specifically catches FileError.notFound and prints "File not found error caught".
Final Answer:
File not found error caught -> Option A
Quick Check:
Throw and catch specific error = prints catch message [OK]
Hint: Throws matching catch block runs, prints its message [OK]
Common Mistakes:
Expecting function to return normally
Ignoring specific catch and expecting generic catch
Confusing error thrown with error caught
4. Identify the error in the following Swift code snippet:
enum LoginError: Error {
case invalidUsername
case invalidPassword
}
func login(user: String, password: String) throws {
if user.isEmpty {
throw LoginError.invalidUsername
} else if password.isEmpty {
throw LoginError.invalidPassword
}
}
try login(user: "", password: "1234")
medium
A. Function login should not throw errors
B. Missing do-catch block to handle the thrown error
C. Enum does not conform to Error protocol
D. Invalid enum case names
Solution
Step 1: Check enum conformance
The enum correctly conforms to the Error protocol with valid cases.
Step 2: Analyze function call
The function is called with try but outside a do-catch block or without try? or try!, causing a compile-time error.
Final Answer:
Missing do-catch block to handle the thrown error -> Option B
Quick Check:
Throwing function call needs do-catch or try? [OK]
Hint: Use do-catch when calling throwing functions [OK]
Common Mistakes:
Calling throwing function without do-catch
Assuming enum conformance is missing
Misunderstanding error handling syntax
5. You want to create a custom error enum DatabaseError that conforms to Error and includes cases for connectionFailed, queryFailed, and timeout. Additionally, you want to add a computed property message that returns a user-friendly description for each case. Which of the following is the correct implementation?
hard
A. struct DatabaseError: Error {
var message: String
}
B. enum DatabaseError {
case connectionFailed
case queryFailed
case timeout
var message: String {
return "Error occurred"
}
}
C. enum DatabaseError: Error {
case connectionFailed
case queryFailed
case timeout
var message: String {
switch self {
case .connectionFailed: return "Connection failed"
case .queryFailed: return "Query failed"
case .timeout: return "Operation timed out"
}
}
}
D. enum DatabaseError: Error {
case connectionFailed(String)
case queryFailed(String)
case timeout(String)
var message: String {
return "Error"
}
}
Solution
Step 1: Confirm enum conforms to Error and defines cases
enum DatabaseError: Error {
case connectionFailed
case queryFailed
case timeout
var message: String {
switch self {
case .connectionFailed: return "Connection failed"
case .queryFailed: return "Query failed"
case .timeout: return "Operation timed out"
}
}
} correctly declares an enum conforming to Error with the required cases.
Step 2: Check computed property implementation
The computed property message uses a switch on self to return descriptive strings for each case.
Final Answer:
enum with computed property and switch -> Option C
Quick Check:
Enum + Error + computed property with switch = enum DatabaseError: Error {
case connectionFailed
case queryFailed
case timeout
var message: String {
switch self {
case .connectionFailed: return "Connection failed"
case .queryFailed: return "Query failed"
case .timeout: return "Operation timed out"
}
}
} [OK]
Hint: Use enum with switch in computed property for messages [OK]
Common Mistakes:
Not conforming enum to Error
Using struct instead of enum for error cases
Ignoring switch on self in computed property
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.