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 Error Handling Handling Errors

Lana Wong
Lana Wong
3,968 Points

I'm confused on the HINT

INSTRUCTIONS:

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.

I am confused on what the HINT is telling me.

error.swift
enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

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

  func parse() throws {
guard let someKey = data["someKey"] else {
throw ParserError.invalidKey
}
  }
}

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

1 Answer

Chris Stromberg
PLUS
Chris Stromberg
Courses Plus Student 13,389 Points

First check to make sure data is not nil, if it is, throw the PaserError so you can exit the function without crashing.

guard let validData = data else {
            throw ParserError.emptyDictionary
        }

Second you need to create an Array that holds all of the keys of your dictionary, using the .keys property.. This array will only contain the keys for your dictionary. You can use the .contains property on this array to check for the String you supply as an argument. This will return a bool, if false is returned, you will throw an error.

        let dataKeys = Array(validData.keys)

        guard dataKeys.contains("someKey") else {
            throw ParserError.invalidKey
        }
    }