iOS Error Handling in Swift Error Handling Handling Errors

Jonathan Abdon
Jonathan Abdon
1,172 Points

what's wrong with my code?

I followed the instructions but still getting error that says try again. I can figure out why it is not letting me going to next task

error.swift
enum ParserError: Error {
    case emptyDictionary
    case invalidKey
}

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

    func parse() throws {
        guard let d: String = (self.data?["someKey"])! else {
            throw ParserError.emptyDictionary
        }

        let keys = self.data?.keys
        guard (keys?.contains("someKey")) != nil else {
            throw ParserError.invalidKey
        }
    }
}

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

2 Answers

Everton Carneiro
Everton Carneiro
5,261 Points

Hello mate. Let's check your code:

    func parse() throws {
        guard let d: String = (self.data?["someKey"])! else {
            throw ParserError.emptyDictionary
        }

        let keys = self.data?.keys
        guard (keys?.contains("someKey")) != nil else {
            throw ParserError.invalidKey
        }
    }

I'm not quite sure what you've tried to do, but this is not the way. In the first guard let statement you are not checking if the dictionary is empty, you are checking a key inside data. If after this you try to catch the erros with a do try catch block you'll notice that .emptyDictionary will be caught if your dictionary has "someKey" inside. Also if you pass an empty dictionary, your app will crash because you force unwrap and the compiler will find nil. Try like this:

    func parse() throws {

//Check if the data dictionary is empty:

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

//Check if there's a key named "someKey" in the data  dictionary:

        guard let value = data["someKey"] else {
            throw ParserError.invalidKey
        }

    }

Of course that in real world projects, I would pass the key as an argument of the function instead of hardcoding "someKey". But for the challenge it's enough. I hope that helps.

Jonathan Abdon
Jonathan Abdon
1,172 Points

Thanks Everton Carneiro.