Last active
August 29, 2015 14:04
-
-
Save ijoshsmith/52a243208aaf092e1c19 to your computer and use it in GitHub Desktop.
Simplifying NSJSONSerialization in Swift
This file contains hidden or 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 | |
/** Outputs of the JSONObjectWithData function. */ | |
enum JSONObjectWithDataResult | |
{ | |
case Success(AnyObject) | |
case Failure(NSError) | |
} | |
/** | |
Attempts to convert the specified NSData to JSON objects | |
and returns either the root JSON object or an error. | |
*/ | |
func JSONObjectWithData( | |
data: NSData, | |
options: NSJSONReadingOptions = nil) | |
-> JSONObjectWithDataResult | |
{ | |
var error: NSError? | |
let json: AnyObject? = | |
NSJSONSerialization.JSONObjectWithData( | |
data, | |
options: options, | |
error: &error) | |
return json != nil | |
? .Success(json!) | |
: .Failure(error ?? NSError()) | |
} | |
// | |
// Example usage | |
// | |
func readSomeJSON() | |
{ | |
// Get JSON data somewhere… | |
let data = NSData() | |
switch JSONObjectWithData(data) | |
{ | |
case .Success(let json): println("json: \(json)") | |
case .Failure(let error): println("error: \(error)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment