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

compiler is not able to detect the error in the code

enum ParserError: ErrorType { case EmptyDictionary case InvalidKey }

struct Parser{ var data: [String : String?]? func parse() throws { guard (data?.keys) != nil else { throw ParserError.EmptyDictionary } guard data?.keys.contains("someKey") != nil else { throw ParserError.InvalidKey } } }

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

do{ parser.data = data try parser.parse() }catch ParserError.InvalidKey{ print("Invalid Key") }

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


struct Parser{
    var data: [String : String?]?
    func parse() throws {
        guard (data?.keys) != nil else {
            throw ParserError.EmptyDictionary
        }
        guard data?.keys.contains("someKey") != nil else {
            throw ParserError.InvalidKey
        }
    }
}


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


do{
    parser.data = data
 try parser.parse()
}catch ParserError.InvalidKey{
    print("Invalid Key")
}

1 Answer

Roberto Pando
Roberto Pando
9,486 Points

Really close, first you're checking if data is completely empty and you can do that by trying to unwrap it, secondly it wants to know if data contains a key named someKey, no need to check if is nil you probably got confused and tried to check that the key someKey was not empty: Your code:

 func parse() throws {
        guard (data?.keys) != nil else {
            throw ParserError.EmptyDictionary
        }
        guard data?.keys.contains("someKey") != nil else {
            throw ParserError.InvalidKey
        }
    }

changed to:

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

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

After that you just need to exhaust the errors by adding a catch block for .EmptyDictionary