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

John Drexler
John Drexler
4,806 Points

This code works fine in xcode. Any tips on how to make it work for Treehouse?

Should this function be returning an instance of Parser?

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

struct Parser {
    var data: [String : String?]?
    func parse(dict: [String: String]) throws {
        guard dict["key"] != nil else {
            throw ParserError.EmptyDictionary
        }

        if dict.keys.contains("someKey") {
        } else {
            throw ParserError.InvalidKey
        }
    }
}

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

1 Answer

Basically, the parse() function has access to the data stored property, so it doesn't need any parameters passed in to it.
You need to see if whatever dictionary that was passed to Parser when an object using the struct is created, and is stored in data, is nil, and if not whether the stored property data has "someKey" as a key:

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

    func parse() throws {
        if data == nil {
            throw ParserError.EmptyDictionary
        }

        if data!.keys.contains("someKey") {  //need to unwrap the optional
        } else {
            throw ParserError.InvalidKey
        }
    }
}