Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
More exploration of guard/try and crazy operator idea
// This is pretty clean, but I often dislike chains of temporary variables
// They tend to lead to little bugs when you use the wrong one. Swift's warnings
// and 'let' reduce problems, though.
func pagesFromOpenSearchData(data: NSData) throws -> [Page] {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
guard let array = json as? [JSON] else { throw JSONError.BadArray(json) }
guard case let value = array[1] where array.count >= 2 else { throw JSONError.OutOfRange }
guard let titles = value as? [String] else { throw JSONError.BadStringList(json) }
return titles.map { Page(title: $0) }
}
// Crazy, but maybe brilliant, idea by @radexp
// https://twitter.com/radexp/status/608754347061706752
infix operator ?! {}
func ?! <T>(a: T?, e: ErrorType) throws -> T {
if let a = a {
return a
} else {
throw e
}
}
// This abandons the step-by-step error checking, which is much of the point of the exercise,
// but is closer to how most people error check. Doesn't need any temporary vriables
func pagesFromOpenSearchData2(data: NSData) throws -> [Page] {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
return try
(json as? [JSON])
.flatMap { $0.count >= 1 ? $0[1] : nil }
.flatMap { $0 as? [String] }
.map { $0.map { Page(title: $0)}}
?! JSONError.BadJSON(json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment