Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,641 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?