Error protocol conformance in Swift - Time & Space Complexity
When we make a type follow the Error protocol in Swift, it helps us handle errors clearly. But how does this affect how long our program takes to run?
We want to see how the time needed changes when we create and use errors this way.
Analyze the time complexity of the following code snippet.
enum FileError: Error {
case notFound
case unreadable
case encodingFailed
}
func readFile(_ name: String) throws -> String {
guard name == "data.txt" else { throw FileError.notFound }
return "File content"
}
This code defines an error type and a function that throws an error if the file name is wrong.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the file name and possibly throwing an error.
- How many times: This check happens once per function call.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: Each call does one check, which takes constant time independent of input size.
Time Complexity: O(1)
This means the time per function call is constant and does not grow with input size.
[X] Wrong: "Making a type conform to Error makes the program slower in a big way."
[OK] Correct: Conforming to Error just adds a simple label to the type. It does not add loops or heavy work, so it does not slow down the program noticeably.
Understanding how error types work and their cost helps you write clear and efficient Swift code. This skill shows you know how to balance safety and speed.
"What if the error type had associated values that needed extra work? How would the time complexity change?"
Practice
Error protocol in Swift?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 DQuick Check:
Error protocol = custom error types [OK]
- Confusing Error protocol with UI or memory management
- Thinking Error protocol manages network connections
- Assuming Error protocol is for general programming tasks
Error protocol?Solution
Step 1: Check enum conformance syntax
To conform to the Error protocol, the enum must explicitly declare: Errorafter its name.Step 2: Verify the enum cases
The cases can be simple without raw values; raw values are optional and unrelated to Error conformance.Final Answer:
enum NetworkError: Error { case disconnected, timeout } -> Option AQuick Check:
Enum conforming to Error = enum Name: Error { cases } [OK]
- Omitting ': Error' conformance
- Using raw value types without conforming to Error
- Confusing enum raw types with protocol conformance
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")
}Solution
Step 1: Analyze the function behavior
The function throwsFileError.notFoundwhen the filename is "missing.txt".Step 2: Check the do-catch block
The catch block specifically catchesFileError.notFoundand prints "File not found error caught".Final Answer:
File not found error caught -> Option AQuick Check:
Throw and catch specific error = prints catch message [OK]
- Expecting function to return normally
- Ignoring specific catch and expecting generic catch
- Confusing error thrown with error caught
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")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 withtrybut outside ado-catchblock or withouttry?ortry!, causing a compile-time error.Final Answer:
Missing do-catch block to handle the thrown error -> Option BQuick Check:
Throwing function call needs do-catch or try? [OK]
- Calling throwing function without do-catch
- Assuming enum conformance is missing
- Misunderstanding error handling syntax
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?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 propertymessageuses a switch onselfto return descriptive strings for each case.Final Answer:
enum with computed property and switch -> Option CQuick 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]
- Not conforming enum to Error
- Using struct instead of enum for error cases
- Ignoring switch on self in computed property
Ready to prove it?
Pass the test and this pattern moves unknown
