Last active
August 29, 2015 14:07
-
-
Save pyrtsa/7460b4bdd098f8b51800 to your computer and use it in GitHub Desktop.
Playing with JSON input on the Swift playground
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
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