Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using protocols like Equatable or Codable instead of Error.
Forgetting to conform to any protocol.
✗ Incorrect
In Swift, to create a custom error type, you declare an enum that conforms to the Error protocol.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing a protocol name like Error instead of a concrete error case.
Throwing a String or NSError directly.
✗ Incorrect
You throw an instance of your custom error type, here NetworkError.badURL.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using other protocols instead of Error.
Not conforming to any protocol.
✗ Incorrect
To make FileError an error type, it must conform to the Error protocol.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching enum name in throw statement.
Not conforming enum to Error protocol.
✗ Incorrect
The enum ValidationError conforms to Error and is used to throw invalidInput error.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not conforming to Error protocol.
Returning a non-string value in localizedDescription.
✗ Incorrect
CustomError conforms to Error and provides a localizedDescription string.