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

Alwin Lazar V
Alwin Lazar V
5,267 Points

Please give me the answer I don't understand

give me code and fill with comments to explain what is it

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

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

   func parse() throws {
        if data == nil {
            throw ParserError.EmptyDictionary
        }

        if data!["someKey"] == nil {
            throw ParserError.InvalidKey
        }
    }
}

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

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! While I could give you the exact code for the first step, I feel like it would be a better overall learning experience for you if you receive some hints first and try it from there. So let's try that first!

  • Use guard and else instead of ìf
  • Check the capitalization of your error messages and make sure they match what was defined in the enum
  • You are trying to look at the value of "someKey" instead of determining if "someKey" exists.
  • Use data.keys to retrieve a list of keys
  • Use the contains method on the retrieved keys to see if "someKey" is among them
  • Use ? to unrwrap your data

Hope this helps, but let me know if you're still stuck! :sparkles:

Aurelian Spodarec
Aurelian Spodarec
10,801 Points

Jennifer, do you know everything? : p

Aurelian Spodarec
Aurelian Spodarec
10,801 Points

Re watch. I can build you a whole App, but it's not that you will know how to do it your self.

Alwin Lazar V
Alwin Lazar V
5,267 Points

okey just give me few hints

Aurelian Spodarec
Aurelian Spodarec
10,801 Points

I don't sit in the App code, but what I mean that the best thing is to re-watch it again, or even the whole section, you might not even get any response. I don't sometimes.