Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Error Handling in Swift Error Handling Handling Errors

Where did I go Wrong. I doing fine its telling me "Make sure you're calling the parse method!" but [someKey] ...

guard let key = !data["someKey"] is coming up wrong?

error.swift
enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

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

  func parse() throws {
guard let data = data else {
  throw ParserError.emptyDictionary
  }
  guard let key = !data["someKey"] else {
      throw ParserError.invalidKey
}
  }
}


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

} catch ParserError.emptyDictionary {
 print("type something") // deals with the empty dictionary
} 
catch 
    ParserError.invalidKey {
        print("wrong key")  // deals with invalid key
}
nicholasdevereaux
nicholasdevereaux
16,353 Points

It looks like you moved the parser constant that was provided to the "do" block. Now you're using "try" twice...once to initialize a Parser struct and another to call parse(). Remove your first try statement and put back the constant "parser" that was provided with the question and it should work.

enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

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

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

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

do {
    let validData = try parser.parse()
} catch {
  print("Error: \(error)")
}

1 Answer

Thanks I did try twice! Happy Holidays!