[英]fatal error: unexpectedly found nil while unwrapping an Optional value using Dictionary for valid JSON
As the title states, I am receiving the "fatal error: unexpectedly found nil while unwrapping an Optional value" error. 如标题所示,我收到“致命错误:在展开可选值时意外发现nil”错误。 My JSON is valid, and the link can be found here: http://www.mocky.io/v2/5844d2801100001d140e6b91 .
我的JSON有效,可以在这里找到链接: http : //www.mocky.io/v2/5844d2801100001d140e6b91 。
The line of code that is giving me an issue is here: 给我一个问题的代码行在这里:
let fighterDetails = dictionary["Fighters"]! as! [[String:AnyObject]]
At one point, I had all working code. 一方面,我拥有所有有效的代码。 I went back and re-structed my entire code as I decided to change the topic.
当我决定更改主题时,我回去重新构建了我的整个代码。 I fixed all other errors, but I'm left with this at run-time.
我修复了所有其他错误,但在运行时将其保留了下来。
When parsing remote JSON data, you should never use the !
解析远程JSON数据时, 切勿使用
!
operator. 操作员。 Instead, use
guard
statements when unwrapping: 而是在展开包装时使用
guard
语句:
guard let fighterDetails = dictionary["Fighters"] as? [[String:AnyObject]] else {
return []
}
And use try?
并
try?
使用try?
instead of try!
而不是
try!
. 。
For the client developer, I recommend the usage of SwiftLint to help you use better Swift practices. 对于客户端开发人员,我建议使用SwiftLint来帮助您使用更好的Swift做法。 It would have detected the issue with
as!
它将检测到
as!
的问题as!
. 。
For the server developer, I recommend to stick to one lettercase convention. 对于服务器开发人员,我建议遵循一个字母大写的约定。 People tend to recommend camelCase when dealing with JSON keys .
人们在处理JSON密钥时倾向于推荐camelCase 。 ie, you should rename "Fighters" to "fighters" to align with "name", "country", ... It may have avoided the issue of your missing key.
即,您应该将“战斗机”重命名为“战斗机”,以与“名称”,“国家/地区”保持一致。...这样可以避免丢失密钥的问题。
我检查了json网址,那里没有键“ Fighters”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.