iOS Error Handling in Swift Error Handling Handling Errors

I'm not sure what I'm doing wrong in regards to this exercise.

I'm hoping someone could help me out with this exercise. I'm not entirely sure why this is failing.

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

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

  func parse() throws {

        guard let newdata = data else {
             throw ParserError.emptyDictionary 
        }
        let keys = newdata.keys 

            for x in keys {
            if keys.contains(x)  {
                if let data = newdata[x] {
                        //do something with data
                }
            }else {
                throw ParserError.invalidKey
            }

        }

  }
}

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

1 Answer

Jhoan Arango
MOD
Jhoan Arango
Treehouse Moderator 12,548 Points

Hello,

Here is an answer that may help you solve your problem !

enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

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

  func parse() throws {

        // Here we check for a condition
        guard data?.isEmpty == false else {
            throw ParserError.emptyDictionary
        }

       // Here we unwrap the keys, and then check for a condition,
        guard let keys = data?.keys, keys.contains("someKey") else {
            throw ParserError.invalidKey
        }
   }
}

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

When unwrapping an optional value, remember to create a temporary store property.

// example

guard let someProperty = someOptional else { return }

Hope this helps

Good luck

Also don't forget that if this answer helps you understand better, don't forget to select as best answer, to help others find a good answer. Or if you need a better explanation please let me know.