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

Error handling using guard statement compiles but does not throw correct error!

I'm trying to implement error handling using a guard statement as described by the Instructor.

Here is the problem assigned: Challenge Task 1 of 3

In the editor, you have a struct named Parser whose job is to deconstruct information from the web. The incoming data can be nil, keys may not exist, and values might be nil as well. In this task, complete the body of the parse function. If the data is nil, throw the EmptyDictionary error. If the key "someKey" doesn't exist throw the InvalidKey error. Hint: To get a list of keys in a dictionary you can use the keys property which returns an array. Use the contains method on it to check if the value exists in the array

If you take a look at my code i'm throwing the right error. However, the automatic grading response "is that I need to throw the InvalidKey error which is what I'm throwing, so I'm unclear as to why this is the case.

below is my code.

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

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

  func parse() throws {
   guard let notEmpty = data?.keys else {
    throw ParserError.EmptyDictionary
    }
   guard let hasKey = data?.keys.contains("someKey") else {
    throw ParserError.InvalidKey
    }
  }
}

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

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Damion Marshall,

You need to check if the data property is empty not if the keys are empty. Your next problem is that the contains() method returns a boolean value. So the chain of operations data?.keys.contains("someKey") will result in a Bool and not an optional type.

Check one of my previous responses for more information:

https://teamtreehouse.com/community/error-handling-2

Good Luck