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 Error Handling Handling Errors

Martel Storm
Martel Storm
4,157 Points

Handling Errors! I can't Handle it!

Isn't this supposed to pass?

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

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

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

        guard data["somekey"] != nil else {
            throw ParserError.InvalidKey
        }

    }
}

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

1 Answer

Nathan Tallack
Nathan Tallack
22,160 Points

Yeah, your code is good, but the workspace unit tests don't really like you changing stuff that have already coded for. In this case you changed the case of your error enum items.

Your code would look like this without those changes.

enum ParserError: Error {
  case emptyDictionary
  case invalidKey
}

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

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

        guard data["someKey"] != nil else {
            throw ParserError.invalidKey
        }
  }
}

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

do {
    let parser = Parser(data: data)
    try parser.parse()
} catch ParserError.emptyDictionary {
} catch ParserError.invalidKey {
}
Martel Storm
Martel Storm
4,157 Points

You're basically a god. Thank you.