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

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!!