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

Trevor Wood
Trevor Wood
17,828 Points

I couldn't figure how to do this without using the bang operator. Did I solve this the right way?

I know Pasan told us not to use the bang operator but I couldn't figure out how to unwrap the optional and keep it unwrapped.

enum ParserError: ErrorType {
    case EmptyDictionary
    case InvalidKey

}


struct Parser {

    var data: [String : String?]?

    func parse() throws {

        let dataUnwrapped = data

        if (dataUnwrapped == nil) {
            throw ParserError.EmptyDictionary
        }

        if (dataUnwrapped!["someKey"] == nil){
            throw ParserError.InvalidKey
        }

    }
}


let data1: [String : String?]? = ["someKey": nil]
var data2: [String : String?]? = nil
var data3: [String : String?]? = ["wrongKey": nil]
let parser = Parser(data: data3)


do {
    try parser.parse()
    print("Parsed w/o errors")
} catch ParserError.EmptyDictionary {
    print("Dictionary is Empty")
} catch ParserError.InvalidKey {
    print("Key is Invalid")
}
Steven Deutsch
Steven Deutsch
21,046 Points

Hey Trevor Wood,

I would recommend using "if let" or "guard let" to optional bind. You should be able to google this topic and find some good examples and then re-adjust your code to implement them.

Good Luck

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points

Hello :

Here is a simple explanation using guards, which I think it's best suited for this...

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

    func parse() throws {

// If the dictionary is empty, then it will throw the error. 
// This way, you can use the "data" constant on the next guard statement. 

        guard let data = data else {
            throw ParserError.EmptyDictionary
        }

// Here we are using the "data" constant from the guard above
// which was already guarded, therefore you don't need to unwrap it. 
// If you wanted to use the data dictionary instead, you would use self.data!.keys.contains() 

        guard data.keys.contains("someKey") else {
            throw ParserError.InvalidKey
        }

    }
}

Good luck

Trevor Wood
Trevor Wood
17,828 Points

Thanks Jhoan! I'll have to rewatch the guard video.