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

How to check if Dictionary is nil

I know I can use a guard let statement to check whether or not a key exists, but I dont remember a lesson on how to check whether or not an entire dictionary contains data? Maybe something like [key : value] ????

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

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

  func parse() throws {
  if let data = [nil : nil] { throw ParserError.EmptyDictionary }
 guard let key = data["someKey"] else { throw ParserError.InvalidKey } 

  }
}

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

1 Answer

Jari Koopman
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jari Koopman
Python Web Development Techdegree Graduate 29,349 Points

Hi Elijah,

If you want to get what I think you want to get (just checking if there's anything in the dictionary) you can just use the not operator like this:

var dict: [String: AnyObject]
if dict != nil {
 //Now you know it's not nil, so it contains someting
}

Hope this helped!

Kind regards, Jari