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 trialjoelbumpus
3,354 PointsStuck and need help, please.
What am I missing or have incorrect here in my code?
enum ParserError: ErrorType {
case EmptyDictionary
case InvalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
guard (data?["someKey"]) != nil else {
throw ParserError.invalidKey
}
guard (data?.keys) != nil else {
throw ParserError.emptyDictionary
}
}
let data: [String : String?]? = ["someKey": nil]
do {
let parser = try Parser(data: data).parse()
} catch {
print("Error")
}
2 Answers
Jeff McDivitt
23,970 PointsHi Joel -
You are very close. I did task 1 differently but I believe you way will work. I believe you will see what you are missing by taking a look at the code below
enum ParserError: Error {
case emptyDictionary
case invalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
guard let data = data else {
throw ParserError.emptyDictionary
}
guard data["somekey"] != nil else {
throw ParserError.invalidKey
}
}
}
let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)
do {
let parser = try Parser(data: data)
try parser.parse()
} catch ParserError.emptyDictionary(let description) {
print(description)
}
catch ParserError.invalidKey(let description) {
print(description)
}
joelbumpus
3,354 PointsJeff, this worked perfectly. Thank you for the explanation and clarity here!