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

boris said
boris said
3,607 Points

guard statement is saying dict["(array key)"] is invalid. Please help, I have always used this before.

Thank you in advance for your help

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

struct Parser {

  var data: [String : String?]?

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

  }

  }
}

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

3 Answers

Oliver Duncan
Oliver Duncan
16,642 Points

The problem here is that there is no dictionary named 'dict', the dictionary is named 'data'.

enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey
}

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

  func parse() throws {
   guard let data = data else { throw ParserError.EmptyDictionary } // could also be written if data == nil { throw ParserError.EmptyDictionary }
   guard let someKey = data["someKey"] else { throw ParserError.InvalidKey }
  }
}

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

First, we check if data is nil. If it is, we throw ParserError.EmptyDictionary. Then, we check if 'someKey' exists in data. If it doesn't, we throw ParserError.InvalidKey.

I think the challenge description is a little misleading. An empty dictionary is not nil, it's just an empty dictionary. And you don't have to use data.keys at all! You just check if the value of data['someKey'] is nil. Anyway, hope this helps.

boris said
boris said
3,607 Points

Thanks for the help, you've got me back on track.

boris said
boris said
3,607 Points

I am also having errors with the next part, Here is the code for the catch task.

catch {

try Parser.parse()

}

It is giving me several errors no matter how I change it? Can you please help?