Last active
July 12, 2016 01:29
-
-
Save rnapier/dbffbf54274a880a6ac7 to your computer and use it in GitHub Desktop.
More exploration of guard/try and crazy operator idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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