Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijoshsmith/52a243208aaf092e1c19 to your computer and use it in GitHub Desktop.
Save ijoshsmith/52a243208aaf092e1c19 to your computer and use it in GitHub Desktop.
Simplifying NSJSONSerialization in Swift
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