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!

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

Paul Je
Paul Je
4,435 Points

Unsure on how I can create throw functions for both cases properly

Is the syntax just a different way to approach it? Maybe I'm not understanding fully how to differentiate a case where a key value doesn't exist and when a value is nil; it seems a little similar to me. Is the 'data' referring to the value, not the key? Thanks...

enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey

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

  func parse() throws {

  guard var someKey = dict["data"] == nil {
    throw ParserError.EmptyDictionary("the data itself is nil")
  } else {  
  throw ParserError.InvalidKey("the key is invalid since it dont exist in the dictionary!")



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

1 Answer

Ben Shockley
Ben Shockley
6,094 Points

You are correct in that the data is referring to the VALUE in the dictionary. The KEY of the dictionary is a way to identify the data that is stored in the VALUE.

So an example to differentiate the two cases might be something like this.

Say you have a dictionary containing information about a user, so it might look something like this.

let userInformation = ["first name": "Frank", "middle name": nil, "last name": "Lemons", "age": 39]

so if you tried to access the KEY called "social security number" that would be an invalid key error since there isn't even an entry for "social security number" in the dictionary, it doesn't exist at all.

But say you want to get the user's middle name. Well "Frank" up there has a KEY for "middle name", but he doesn't have a middle name, so that VALUE was stored as nil. So for this case you would throw the EmptyDictionary error since that VALUE will return a nil if you try to pull it.

Does that make sense at all? Am I hitting on what you're having trouble with?

In essence they kind of are the same, but depending on your program, you might want to know if the error is that the KEY your looking just doesn't exist, or if the VALUE for that KEY is empty.