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 can't figure out an answer

This is the code

enum ParserError: ErrorType {
    case EmptyDictionary
    case InvalidKey
}

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

    func parse() throws {

    }
}

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

Task is: 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.

I really don't know where to start. Any help?

I have tried with

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

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

and it passes but in next stage I get varius errors that are realated with this code that passed.

1 Answer

Michael Reining
Michael Reining
10,101 Points

Hi Antonija,

Thanks for helping me with part 1 of the challenge. I can now return the favor.

Here is how I solved part 2 of the challenge.

enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey
}

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

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

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

    }
}

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

do {
    try parser.parse()
} catch {
    print("\(error)")
}

I hope that helps,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.

Now you can practice writing Swift code directly on your iPhone :-)

Code! Learn how to program with Swift

ahhh I was "do-catching" the wrong thing. Thanks!