Bird
Raised Fist0
Swiftprogramming~20 mins

Error protocol conformance in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift error handling code?

Consider the following Swift code that defines an error and uses do-catch to handle it. What will be printed?

Swift
enum MyError: Error {
    case badInput
}

func testError() throws {
    throw MyError.badInput
}

do {
    try testError()
    print("No error")
} catch MyError.badInput {
    print("Caught badInput error")
} catch {
    print("Caught some other error")
}
ACaught badInput error
BCompilation error
CCaught some other error
DNo error
Attempts:
2 left
💡 Hint

Think about which error is thrown and which catch block matches it.

❓ Predict Output
intermediate
2:00remaining
What error does this Swift code raise?

Given this Swift code, what error will be raised at runtime?

Swift
struct NotAnError {}

func throwSomething() throws {
    throw NotAnError()
}

try? throwSomething()
AType 'NotAnError' does not conform to protocol 'Error'
BNo error, code runs fine
CRuntime error: unexpected non-Error thrown
DCompilation error: missing throws keyword
Attempts:
2 left
💡 Hint

Check if the thrown type conforms to the Error protocol.

🔧 Debug
advanced
2:00remaining
Why does this Swift code fail to compile?

Examine the code below. Why does it fail to compile?

Swift
enum CustomError: Error {
    case errorOne
}

func mightThrow(_ flag: Bool) throws {
    if flag {
        throw "Error occurred"
    }
}

try? mightThrow(true)
AMissing throws keyword in function signature
BString does not conform to Error protocol
CCannot throw from non-throwing function
DEnum cases must have associated values
Attempts:
2 left
💡 Hint

Look at the type being thrown inside the function.

🧠 Conceptual
advanced
2:00remaining
Which Swift type correctly conforms to the Error protocol?

Which of the following Swift types correctly conforms to the Error protocol?

Aenum MyError {}
Bclass MyError {}
Cstruct MyError: CustomStringConvertible {}
Dstruct MyError: Error {}
Attempts:
2 left
💡 Hint

Remember that to be throwable, a type must explicitly conform to Error.

❓ Predict Output
expert
3:00remaining
What is the output of this Swift error handling with pattern matching?

Analyze the following Swift code. What will it print?

Swift
enum NetworkError: Error {
    case timeout
    case serverError(code: Int)
}

func fetchData() throws {
    throw NetworkError.serverError(code: 500)
}

do {
    try fetchData()
} catch NetworkError.timeout {
    print("Timeout occurred")
} catch NetworkError.serverError(let code) where code >= 500 {
    print("Server error with code \(code)")
} catch {
    print("Other error")
}
ATimeout occurred
BOther error
CServer error with code 500
DCompilation error
Attempts:
2 left
💡 Hint

Check the thrown error and the pattern matching in the catch clauses.

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

  1. Step 1: Understand the role of the Error protocol

    The Error protocol is designed to let developers define their own error types in Swift.
  2. Step 2: Identify the purpose of custom error types

    Custom error types allow throwing and catching specific errors in code, improving error handling.
  3. Final Answer:

    To define custom error types that can be thrown and caught -> Option D
  4. 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
  • Thinking Error protocol manages network connections
  • Assuming Error protocol is for general programming tasks
2. Which of the following is the correct way to declare an enum that conforms to the Error protocol?
easy
A. enum NetworkError: Error { case disconnected, timeout }
B. enum NetworkError { case disconnected, timeout }
C. enum NetworkError: String { case disconnected, timeout }
D. enum NetworkError: Int { case disconnected, timeout }

Solution

  1. Step 1: Check enum conformance syntax

    To conform to the Error protocol, the enum must explicitly declare : Error after its name.
  2. Step 2: Verify the enum cases

    The cases can be simple without raw values; raw values are optional and unrelated to Error conformance.
  3. Final Answer:

    enum NetworkError: Error { case disconnected, timeout } -> Option A
  4. Quick Check:

    Enum conforming to Error = enum Name: Error { cases } [OK]
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

  1. Step 1: Analyze the function behavior

    The function throws FileError.notFound when the filename is "missing.txt".
  2. Step 2: Check the do-catch block

    The catch block specifically catches FileError.notFound and prints "File not found error caught".
  3. Final Answer:

    File not found error caught -> Option A
  4. 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

  1. Step 1: Check enum conformance

    The enum correctly conforms to the Error protocol with valid cases.
  2. 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.
  3. Final Answer:

    Missing do-catch block to handle the thrown error -> Option B
  4. 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

  1. 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.
  2. Step 2: Check computed property implementation

    The computed property message uses a switch on self to return descriptive strings for each case.
  3. Final Answer:

    enum with computed property and switch -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard