try-catch放置将Swift字典转换为JSON字符串

问题描述 投票:3回答:1

这是我得到的:

        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")
        }

我收到错误try must be placed on the initial value expression。我像这样尝试'改述':

        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")
        }

但这会导致错误Call can throw but is not marked with 'try'。我应该如何构建这个try-catch以及这些错误代码的含义是什么?

swift try-catch
1个回答
4
投票

你必须改变你放置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")
    }
© www.soinside.com 2019 - 2024. All rights reserved.