iOS Error Handling in Swift Error Handling Handling Errors

swift_lint.swift:16:26: error: use of unresolved identifier 'somekey' guard let someKey = dict[somekey] else {

no idea what they talking about

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

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

  func parse(dict:[String : String]) throws -> Parser {
guard let data = dict[data] else {

throw ParserError.emptyDictionary
}
guard let someKey = dict[somekey] else {

throw ParserError.invalidKey
}
  }
}

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

2 Answers

Hi JC Laurent,

As far as I can see your question is referring to objective 1 of the challenge.

The reason the compiler is throwing that error is because you are trying to access a dictionary of Strings and someKey is not a string.

With regards to the question, you must first unwrap the the dictionary itself as it is an optional dictionary. To do this you can use a guard statement:

  func parse() throws {
    guard let someData = data else {
      throw ParserError.emptyDictionary
    }

Whilst unwrapping your dictionary, you have actually attempted to unwrap an optional piece of data in said dictionary but you must unwrap the whole dictionary first.

Once it is unwrapped, you can THEN unwrap the optional key value using the constant 'someData' that you created in th guard statement. Remember, this constant now has a dictionary assigned for which you can use the keys property and the contains method:

    guard someData.keys.contains("someKey") else {
      throw ParserError.invalidKey
    }

This part of the function checks your unwrapped dictionary assigned to someData for the value "someKey" or a simple string. If a string is contained in the keys of someData then everything works. If however no keys exist in someData, then the error is thrown.

I hope this information helps with this tricky code challenge.

If you have any problems with the next objectives of the challenge don't hesitate to ask.

All the best,

Mitch

Hi Mitch,

I warmly thank you for your help. what you're calling a tricky challenge, I call it unclear code challenge's instructions.

best

Quite often that is the case.

No problem!