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 trialWill Van de Walle
2,352 PointsOverall really confused
This code really doesn't help much, as I haven't made any changes, but I am confused as to what the syntax for this challenge is. I am digging around, but do I use guard let? Or if? Please help.
enum ParserError: ErrorType {
case EmptyDictionary
case InvalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
}
}
let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)
2 Answers
Jhoan Arango
14,575 PointsHello :
There are different ways of doing it.. you can use guard, or you can you if let. But I recommend guard, since it cleaner, and its always good to exit the function early.
struct Parser {
var data: [String : String?]?
// Here we indicate that this method, can throw an error
func parse() throws {
// The guard is used as a way to check if there is an error, and if there is, what type of error is it
guard let data = data else {
throw ParserError.EmptyDictionary
}
// This guard checks if the key exist, and it throws the type of error "invalidKey" if it does not.
guard let key = data["someKey"] else {
throw ParserError.InvalidKey
}
}
}
let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)
Hope this helps you a bit.
Good luck
Christian McMullin
13,086 Pointsthe challenge says to use the contains method to check for "someKey"
enum ParserError: ErrorType {
case EmptyDictionary
case InvalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
guard let someData = data else {
throw ParserError.EmptyDictionary
}
guard let keys = data?.keys where keys.contains("someKey") else {
throw ParserError.InvalidKey }
}
}
let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)