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 2.0 Error Handling Handling Errors

Manuel Pascual
Manuel Pascual
4,676 Points

I really don't know how to pass this challenge... Need help!

I really don't know how to pass this challenge... Need help!

error.swift
enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey
}

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

  func parse(dict: [String : String?]?) throws {
        guard let diccionario = dict else {
            throw ParserError.EmptyDictionary
        }
        guard let emptyKey = dict?["someKey"] else {
            throw ParserError.InvalidKey
        }
    }
}

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

2 Answers

Victor Santos
Victor Santos
3,585 Points

The Struct β€œParse” it's expecting a "data" and this data you should to pass to the function β€œparse", so you do not need to add additional parameters, and them you should to validate whether guard (data != nil) else{ throw} and guard let someVar = data["someKey"] else{ throw } remember the exclamation mark data!["someKey"]

enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey
}

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

  func parse() throws {
    guard (data != nil)  else {
      throw ParserError.EmptyDictionary
    }
    guard let someKey = data!["someKey"] else {
      throw ParserError.InvalidKey
    } 
  }
}

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

Try this for the struct for the 1st part:

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
        }

    }
}

Note that the parse() function has no parameters, and that this version uses the stored property data. Otherwise you were pretty much there.