Bird
0
0

You want to write a function loadData() that throws a custom error DataError.invalidFormat if data is bad. Which code correctly defines the error and throws it inside the function?

hard📝 Application Q15 of 15
iOS Swift - Swift Language Essentials
You want to write a function loadData() that throws a custom error DataError.invalidFormat if data is bad. Which code correctly defines the error and throws it inside the function?
Aclass DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
Bstruct DataError { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
Cenum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
Denum DataError { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
Step-by-Step Solution
Solution:
  1. Step 1: Define a custom error type conforming to Error

    In Swift, custom errors are usually enums conforming to the Error protocol, like enum DataError: Error.
  2. Step 2: Throw the custom error inside the function

    The function loadData() declares throws and throws DataError.invalidFormat correctly.
  3. Final Answer:

    enum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat } -> Option C
  4. Quick Check:

    Custom errors use enum + Error protocol [OK]
Quick Trick: Use enum conforming to Error for custom errors [OK]
Common Mistakes:
  • Not conforming error type to Error protocol
  • Using struct or class without Error conformance
  • Forgetting throws keyword in function

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes