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

Julien Schmitt
Julien Schmitt
2,334 Points

Confused about the statement - Error handling

Hi all,

I'm not sure that I understood well what has to be done in this exercice.

  1. Should I specify a return parameter for the parse function?
  2. "if the data is nil". Which data of what? The constant?
  3. Same question for the "someykey" data.

Thanks,

Julien

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

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

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

        guard let parser = ["someKey": String] else {
            throw ParserError.InvalidKey
        }
  }
}

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

1 Answer

Tassia Castro
seal-mask
.a{fill-rule:evenodd;}techdegree
Tassia Castro
iOS Development Techdegree Student 9,170 Points

No, you shouldn’t. What you have to do is only check if the dictionary ‘data’ is nil and if the key “someKey” exists. If it doesn’t, you throw an error.

The ‘data’ that he means is : var data: [String : String?]?

In the exercise a dictionary called data is created with this value: [“someKey”: nil]. So, inside the func parse, you need to check if this dictionary has indeed a key called “someKey”.

In order to check if the dictionary is nil, you can use the guard statement and it would be something like that:

guard let xValue = x else { // x is what you wanna check if it is nil throw an error }

ps: As the dictionary is not nil, the error will not be thrown.

In order to check if the key exists, use the if statement with the methods that are shown in the quiz. Adapt this if (x) with the dictionary of the quiz.

// if x does not contains (“someKey”), throw an error. if !x.keys.contains(“somekey”) { throw an error }

ps: As the dictionary data has indeed a key called ‘someKey’, this error will not be thrown.