swift - 将 Swift 字典转换为 JSON 字符串时的 try-catch 位置

标签 swift try-catch

这是我得到的:

        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 以及这些错误代码是什么意思?

最佳答案

您必须更改放置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")
    }

关于swift - 将 Swift 字典转换为 JSON 字符串时的 try-catch 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006236/

相关文章:

ios - 如何在单元测试期间以编程方式编辑 iPhone 辅助功能设置?

ios - 如何在 Swift 中使 TableView 的标题 View 可点击

ios - 如何在 iOS 中仅获取可见日历

r - 所有连接都在使用中 : Execution halted

python - 检查文件是否可以用 Python : try or if/else? 读取

ios - WKWebView Inside View 和 Inside ScrollView 失去联系 iOS 9

node.js - 在 Promise catch 上重试 try/catch

PowerShell FTP 未能命中 Catch block

javascript - try {} without catch {} 可以在 JavaScript 中使用吗?

ios - MKMapView 在所有点之间绘制连接线