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

mahi
mahi
7,137 Points

Can't get it?!

Can't figure this one out.

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

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

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

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

    }
}

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

1 Answer

As usual there are several ways of doing this. Here's one version of the function that starts out like you did:

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

        if data!["someKey"] == nil {
            throw ParserError.InvalidKey
        }
    }

But then, instead of using a guard statement, it just tests to see if data["someKey"] is also nil. Note that you will get an error if you don't forcibly unwrap data in this second if statement. Yes, forcibly unwrapping isn't usually a good idea. But here you've already tested to see if it's nil or not, so it's fine here. You know for sure it is not nil, otherwise the function would have thrown the EmptyDictionary error.

mahi
mahi
7,137 Points

Got it. Thanks alot!!