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

Jason Marcial
Jason Marcial
8,162 Points

How to unwrap an optional dictionary without using the force unwrapping operator '!'

My code doesn't compile under teamtreehouse compiler, somehow my code works on xCode but when I submit my code into the website doesn't give me any answer. I believe it's because I'm using the '!' operator. Please help me checking my code, I'll appreciate for your answer. Thanks.

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

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

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

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

2 Answers

Jhoan Arango
Jhoan Arango
14,547 Points

Hello :

Here is a simple explanation...

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

    func parse() throws {

// If the dictionary is empty, then it will throw the error. No need to use the =! nil.
// This way, you can use the "data" constant on the next guard statement. 

        guard let data = data else {
            throw ParserError.EmptyDictionary
        }

// Here we are using the "data" constant from the guard above
// which was already guarded, therefore you don't need to unwrap it. 
// If you wanted to use the data dictionary instead, you would use self.data!.keys.contains() 

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

    }
}

Good luck

Jason Marcial
Jason Marcial
8,162 Points

Thanks Jhoan!! I't really helped me solve my code. Just one little detail you throw the same EmptyDictionary error on both statements. I appreciate your help.

Jhoan Arango
Jhoan Arango
14,547 Points

Thank you for pointing it out, I corrected it.