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

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,575 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,575 Points

Thank you for pointing it out, I corrected it.