Last active
August 29, 2015 14:24
-
-
Save patricklynch/8d5b792c5fa2aad95fe7 to your computer and use it in GitHub Desktop.
Using a switch case to unwrap optionals when parsing JSON data (Swift 1.2)
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 | |
func parse( data: NSData ) { | |
var error: NSError? = nil | |
switch NSJSONSerialization.JSONObjectWithData( data, options: nil, error: &error ) { | |
case .Some(let dictionary as NSDictionary): | |
println( "JSON contained dictionary: \(dictionary)" ) | |
case .Some(let array as NSArray): | |
println( "JSON Contained array: \(array)" ) | |
default: | |
println( "Could not parse: \(error)" ) | |
} | |
} | |
parse( "{\"hello\" : \"world\"}".dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: true)! ) | |
parse( "[\"hello\", \"world\"]".dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: true)! ) | |
parse( "not json".dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: true)! ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment