helloB
helloB

Reputation: 3582

try-catch placement in converting Swift dictionary to JSON string

Here's what I've got:

        do {
            try let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
            jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
        } catch {
            print("CAUGHT SOMETHING session token")
        }

I'm getting an error try must be placed on the initial value expression. I tried 'rephrasing' like so:

        do {
            let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
            try jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
        } catch {
            print("CAUGHT SOMETHING session token")
        }

but this leads to an error Call can throw but is not marked with 'try'. How should I be structuring this try-catch and what do these error codes mean?

Upvotes: 5

Views: 1349

Answers (1)

Kayla Galway
Kayla Galway

Reputation: 672

You have to change the location of where you are putting your try.

    do {
        if let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted) {
          //is jsonString a variable you have previously declared?
          //if not, put "if let" before it, because you are creating it IF:
          //your "try" - attempt to get data from json succeeds
          jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String 
        }
    } catch {
        print("CAUGHT SOMETHING session token")
    }

Upvotes: 6

Related Questions