Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aupajo/f4d231eefefbe7a6ab0d to your computer and use it in GitHub Desktop.
Save Aupajo/f4d231eefefbe7a6ab0d to your computer and use it in GitHub Desktop.
// Decoding JSON
// A JSON string
let data = ...
// We create an optional type which is nil to begin with.
var parseError: NSError?
// We parse the JSON, passing the nil parseError by reference. It will be set to
// an instance of NSError if anything goes wrong.
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.AllowFragments,
error: &parseError)
// Now the madness begins. Each one of these conditionals is checking that the
// value being requested exists and is of the type being asked of it.
if let topApps = parsedObject as? NSDictionary {
if let feed = topApps["feed"] as? NSDictionary {
if let apps = feed["entry"] as? NSArray {
if let firstApp = apps[0] as? NSDictionary {
if let imname = firstApp["im:name"] as? NSDictionary {
if let appName = imname["label"] as? NSString {
println("The app name is: \(appName!)")
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment