0
0
Swiftprogramming~10 mins

Error protocol conformance in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an error type conforming to the Error protocol.

Swift
enum NetworkError: [1] {
    case badURL
    case timeout
}
Drag options to blanks, or click blank then click option'
AError
BEquatable
CCodable
DCustomStringConvertible
Attempts:
3 left
💡 Hint
Common Mistakes
Using protocols like Equatable or Codable instead of Error.
Forgetting to conform to any protocol.
2fill in blank
medium

Complete the code to throw a custom error conforming to Error protocol.

Swift
func fetchData(from url: String) throws {
    guard url.hasPrefix("http") else {
        throw [1].badURL
    }
}
Drag options to blanks, or click blank then click option'
AError
BString
CNSError
DNetworkError
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing a protocol name like Error instead of a concrete error case.
Throwing a String or NSError directly.
3fill in blank
hard

Fix the error in the code to properly conform to the Error protocol.

Swift
struct FileError: [1] {
    let message: String
}
Drag options to blanks, or click blank then click option'
ACodable
BEquatable
CError
DCustomStringConvertible
Attempts:
3 left
💡 Hint
Common Mistakes
Using other protocols instead of Error.
Not conforming to any protocol.
4fill in blank
hard

Fill both blanks to define and throw a custom error conforming to Error protocol.

Swift
enum [1]: [2] {
    case invalidInput
}

func validate(input: String) throws {
    if input.isEmpty {
        throw [1].invalidInput
    }
}
Drag options to blanks, or click blank then click option'
AValidationError
BError
CString
DCustomError
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching enum name in throw statement.
Not conforming enum to Error protocol.
5fill in blank
hard

Fill all three blanks to create a custom error with a localized description.

Swift
struct [1]: [2] {
    var localizedDescription: String {
        return [3]
    }
}
Drag options to blanks, or click blank then click option'
ACustomError
BError
C"An error occurred"
D"Error"
Attempts:
3 left
💡 Hint
Common Mistakes
Not conforming to Error protocol.
Returning a non-string value in localizedDescription.