Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Error Handling in Swift Error Handling Handling Errors

In the editor, you have a struct named Parser whose job is to deconstruct information from the web. The incoming data ca

am close what am i missing

error.swift
enum ParserError: Error {
    case EmptyDictionary
    case InvalidKey
}

struct Parser {
    var data: [String : String?]?

    func parse() throws {
        guard let parsedData = data else {
            throw ParserError.EmptyDictionary
        }
        guard parsedData.keys.contains("someKey") else {
            throw ParserError.InvalidKey
        }
    }
}
let data: [String : String?]? = ["someKey": nil]

do {
  let parser = try Parser(data: data).parse()
} catch let error {
    print(error)
}
Joe Mayfield
Joe Mayfield
10,409 Points

Take a look at the ParserError.EmptyDictionary and the ParserError.InvalidKey. Then compare them to the original once fixed I think it will work.

1 Answer

Otto linden
Otto linden
5,857 Points

Hello! This is the code:

enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

struct Parser {
  var data: [String : String?]?

  func parse() throws {
        guard let parsedData = data else {
        throw ParserError.emptyDictionary
    }
    guard parsedData.keys.contains("someKey") else {
        throw ParserError.invalidKey
    }
  }
}

let data: [String : String?]? = ["someKey": nil]
let parser = try Parser(data: data)

do {
  try parser.parse()
} catch ParserError.emptyDictionary {
    print("Help")
} catch ParserError.invalidKey {
    print("Help!")
}

(You did the do catch statement wrong!)