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

Sara Worth
Sara Worth
5,225 Points

Not sure why this isn't passing?

I'm getting the error: "If the key does not exist, make sure to throw the InvalidKey error." I'm pretty sure I've done that so I'm not sure what's wrong.

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

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

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

        guard (data?["someKey"]) != nil else {
            throw ParserError.emptyDictionary
        }
  }
}

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

1 Answer

Chase Marchione
Chase Marchione
155,055 Points

Interestingly enough, the challenge passes if the equality operator is set to equals for the first guard statement.

guard (data?.keys.contains("someKey")) == nil else {

Curious stuff, but hope this helps in the meanwhile!