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

Jeff Ripke
Jeff Ripke
41,989 Points

Perfect! We're almost done. Rather than a generic catch clause, let's pattern match on the specific errors so that we ca

Unable to figure this out, what am I doing wrong?

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

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

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

let data: [String : String?]? = ["someKey": nil]

do {
    let data: [String : String?]? = ["someKey": nil]
    let parser = try Parser(data: data)
    try parser.parse()
    try parser.data
} catch ParserError.EmptyDictionary {
    print("no data")
} catch ParserError.InvalidKey {
  pring("invalide key")
}

1 Answer

Michael Reining
Michael Reining
10,101 Points

Hi Jeff,

You are super close. Just update your syntax for the error handling like this. You do have a typo, however, that might cause the problem.

  pring("invalide key") // change pring to print ;)

My final code looked like this. I did not even print anything.

enum ParserError: ErrorType {
    case EmptyDictionary
    case InvalidKey
}

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

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

        guard let key = data["somekey"] else {
            throw ParserError.InvalidKey
        }

    }
}

let data: [String : String?]? = ["someKey": nil]
do {
    let parser = try Parser(data: data)
    try parser.parse()
} catch ParserError.EmptyDictionary {
    // deal with empty dictionary
}
catch
    ParserError.InvalidKey {
        // deal with invalid key
}

I hope that helps,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.

Now you can practice writing Swift code directly on your iPhone :-)

Code! Learn how to program with Swift