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.

Gavin Butler
iOS Development with Swift Techdegree Graduate 15,489 PointsIf the key does not exist, make sure to throw the InvalidKey error
I get the above error and nothing in the output file when I use the following code in "Error Handling in Swift/Handling Errors/Task 1 of 3":
guard data != nil else { throw ParserError.emptyDictionary } guard let exists = data?.keys.contains("someKey") else { throw ParserError.invalidKey } guard let keyVal = data?["someKey"] else { throw ParserError.emptyDictionary }
I'm not sure what I'm doing wrong here. Also, is there a better way to write this given that the compiler is telling me that I don't use the 'exists' and 'keyVal' constants?
enum ParserError: Error {
case emptyDictionary
case invalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
guard data != nil else {
throw ParserError.emptyDictionary
}
guard let exists = data?.keys.contains("someKey") else {
throw ParserError.invalidKey
}
guard let keyVal = data?["someKey"] else {
throw ParserError.emptyDictionary
}
}
}
let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)
1 Answer

Gavin Butler
iOS Development with Swift Techdegree Graduate 15,489 PointsDidn't realize that the nil was wrapped as Optional(nil). Solved it with the following code, but think it could be written much better somehow. guard data != nil else { throw ParserError.emptyDictionary } guard true == data?.keys.contains("someKey") else { throw ParserError.invalidKey } if let val = data?["someKey"] { guard val != nil else { throw ParserError.emptyDictionary } }
Gavin Butler
iOS Development with Swift Techdegree Graduate 15,489 PointsGavin Butler
iOS Development with Swift Techdegree Graduate 15,489 PointsDidn't realize that the nil was wrapped as Optional(nil). Solved it with the following code, but think it could be written much better somehow. guard data != nil else { throw ParserError.emptyDictionary } guard true == data?.keys.contains("someKey") else { throw ParserError.invalidKey } if let val = data?["someKey"] { guard val != nil else { throw ParserError.emptyDictionary } }