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 trialGavin 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 } }