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

I'm stuck on this one.

What am I missing here?

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

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

  func parse() throws {
    if data == nil {
      throw ParserError.EmptyDictionary
    }
    if data!.keys.contains("someKey") {
      throw ParserError.InvalidKey
    }

  }
}

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

2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey David Yoo,

I answered this question previously. You can check out my response here: https://teamtreehouse.com/community/error-handling-2

However, I would make one change to my code as recommended by a comment in this thread. Instead of using guard let to unwrap the parser data, we should just do a guard on the data to make sure it is != to nil. This is because we will never be using the value, so it is pointless to bind it to a constant if it will never be used.

Good Luck

You can also do it this way:

    func parse() throws {
        guard let data = data else {
            throw ParserError.EmptyDictionary
        }

        guard let key = data["someKey"] else {
            throw ParserError.InvalidKey
        }
    }