gpt4 book ai didi

ios - 将 JSONObjectWithData 的结果转换为 Dictionary 时发生崩溃

转载 作者:行者123 更新时间:2023-11-28 11:12:09 29 4
gpt4 key购买 nike

应用程序在将 JSON 结果解析为 <String,Any> 时崩溃它不会进入 catch block :

        do
{
result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String,Any>
}
catch let error1 as NSError
{
result = nil
print(error1)
}

如果我将 JSON 结果转换为 <String,AnyObject>它工作正常:

        do
{
result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String,AnyObject>
}
catch let error1 as NSError
{
result = nil
print(error1)
}

不是<Any>协议(protocol)接受原始类型和对象类型,那么它为什么会失败?

最佳答案

您崩溃的原因是您正在强制转换。 Swift 中的 do/catch 构造不像其他语言中的异常那样工作,在其他语言中,任何错误都会在 catch block 中捕获。在你的情况下

NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

可以抛出错误,如果抛出错误,将调用 catch block 。相反,强制转换为 Dictionary 如果失败则不会抛出错误。像这样将类型转换包装在 if let 中会好得多:

do
{
let temp = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

if let result = temp as? Dictionary<String,AnyObject> {
// Do something with the result
}
else {
// cast failed handle it gracefully
}
}
catch let error1 as NSError
{
result = nil
print(error1)
}

现在,为什么转换为“String, AnyObject”时有效,而“String, Any”失败,我怀疑这与以下事实有关:它最初是从您的 JSON 调用返回的 NSDictionary。这些被桥接到 Swift 字典作为“字符串,AnyObject”。现在,您尝试做的事情在技术上应该可行,我认为这是一个错误,但事实并非如此。您可能会考虑针对此行为提交雷达。同时,也建议尽可能避免强制施法。

关于ios - 将 JSONObjectWithData 的结果转换为 Dictionary<String,Any> 时发生崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317337/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com