Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active August 29, 2015 14:07
Show Gist options
  • Save pyrtsa/7460b4bdd098f8b51800 to your computer and use it in GitHub Desktop.
Save pyrtsa/7460b4bdd098f8b51800 to your computer and use it in GitHub Desktop.
Playing with JSON input on the Swift playground
import Foundation
extension String {
func utf8() -> NSData? { return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding) }
}
extension Optional {
func flatMap<U>(transform: T -> U?) -> U? {
if let x = self {
return transform(x)
} else {
return nil
}
}
}
func parseJSON(json: NSData) -> AnyObject? {
return NSJSONSerialization.JSONObjectWithData(json, options: NSJSONReadingOptions(0), error: nil)
}
// Examples:
"{}".utf8().flatMap(parseJSON)
parseJSON("{}".utf8()!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment