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

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
Jhoan Arango
14,575 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.