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

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!